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.
Or try the Ruby 1.9 way:
array.inject(0, :+)
Note: the 0 base case is needed otherwise nil will be returned on empty arrays:
0
nil
> [].inject(:+) nil > [].inject(0, :+) 0
2.1m questions
2.1m answers
60 comments
57.0k users