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.
arraysmathrubysum
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.
Best Answer
For ruby >= 2.4 you can use sum:
array.sum
For ruby < 2.4 you can use inject:
Note: the
0
base case is needed otherwisenil
will be returned on empty arrays: