The simplest way is
array.inject(0, :+)
There is. Where 0
is written to return 0 instead of nil
if x is an empty array.
> [].inject(:+)
nil
> [].inject(0, :+)
0
If Ruby is less than 1.8
array.inject(0){|sum,x| sum + x }
You can replace it with .
© 2024 OneMinuteCode. All rights reserved.