Cumulative array sum in Ruby

Viewed 10303

What is the slickest, most Ruby-like way of calculating the cumulative sum of an array?

Example:

[1,2,3,4].cumulative_sum

should return

[1,3,6,10]
8 Answers

The Haskell function we want is scanl, not scanr.

class Array
  def scanl(init)
    self.reduce([init]) { |a, e| a.push(yield(a.last, e)) }
  end
end

[1,2,3,4].scanl(0) { |a, b| a + b }[1..-1]
=> [1, 3, 6, 10]
Related