How to sum an array of numbers in Ruby?

There are several ways to sum an array. The easiest and most common way in any language is to simply loop over the numbers and add them:

sum = 0
[1, 2, 3].each do |i|
  sum += i

puts sum   # 6 

Most rubyists would rather take advantage of Ruby's Enumerable methods to provide a more concise solution:

[1, 2, 3].inject(0) {|sum, i|  sum + i }

If you are using Ruby 1.8.7 or newer, the following short hand is available.

[1, 2, 3].inject(0, &:+)

'&:+' is simply a shorthand for defining a Proc

If you are using Ruby on Rails, it adds the .sum method for enumerables

[1, 2, 3].sum

Note that this only works with Rails, not with regular Ruby code