How to sum array of numbers in Ruby?
I have an array of integers.
For example:
array = [123,321,12389]
Is there any nice way to get the sum of them?
I know, that
sum = 0
array.each { |a| sum+=a }
would work.
For ruby >= 2.4 you can use sum:
array.sum
For ruby < 2.4 you can use inject:
array.inject(0, :+)
Note: the 0
base case is needed otherwise nil
will be returned on empty arrays:
> [].inject(:+)
nil
> [].inject(0, :+)
0
Try this:
array.inject(0){|sum,x| sum + x }
See Ruby's Enumerable Documentation
(note: the 0
base case is needed so that 0
will be returned on an empty array instead of nil
)
array.reduce(0, :+)
While equivalent to array.inject(0, :+)
, the term reduce is entering a more common vernacular with the rise of MapReduce programming models.
inject, reduce, fold, accumulate, and compress are all synonymous as a class of folding functions. I find consistency across your code base most important, but since various communities tend to prefer one word over another, it’s nonetheless useful to know the alternatives.
To emphasize the map-reduce verbiage, here’s a version that is a little bit more forgiving on what ends up in that array.
array.map(&:to_i).reduce(0, :+)
Some additional relevant reading:
- http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject
- http://en.wikipedia.org/wiki/MapReduce
- http://en.wikipedia.org/wiki/Fold_(higher-order_function)