Calculate A Running Total Of An Array In Ruby
Compute cumulative sums (running totals) — each element in the result is the sum of all preceding elements plus itself. Useful for financial calculations, progress tracking, and time series data.
Description
Use Enumerable#each_with_object or inject to accumulate a running sum. Array#sum gives the total, but for the running total you need to carry state between iterations.
Ruby 2.4+ has Enumerable#sum but not a built-in cumulative sum. The pattern: keep a running accumulator and append it to the result array on each step.
each_with_object is the clearest approach: start with [0] or [], push last + current each iteration.
Sample input:
amounts = [10, 25, 5, 40, 15]
Sample Output:
[10, 35, 40, 80, 95]
Answer
amounts = [10, 25, 5, 40, 15]
# each_with_object — clearest intent
amounts.each_with_object([]) do |val, acc|
acc << (acc.last || 0) + val
end
# => [10, 35, 40, 80, 95]
# inject/reduce
amounts.inject([]) { |acc, val| acc + [acc.last.to_i + val] }
# => [10, 35, 40, 80, 95]
# One-liner via scan (functional style)
amounts.each_with_object([0]) { |v, a| a << a.last + v }.drop(1)
# => [10, 35, 40, 80, 95]
# Running total with index (e.g., for reporting)
amounts.each_with_object([]).with_index do |(val, acc), i|
acc << { day: i + 1, amount: val, cumulative: (acc.last&.dig(:cumulative) || 0) + val }
end
# => [{day:1, amount:10, cumulative:10}, {day:2, amount:25, cumulative:35}, ...]
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀