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.
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.
Alternatively (just for comparison), if you have Rails installed (actually just ActiveSupport):
require 'activesupport'
array.sum
Add sum to the Array class
class Array
def sum
self.inject{|sum,x| sum + x }
end
end
Then do fun stuff like:
[1,2,3,4].sum