How to sum array of numbers in Ruby?

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)

Leave a Comment