How to sum properties of the objects within an array in Ruby

In Ruby On Rails you might also try:

array.sum(&:cash)

Its a shortcut for the inject business and seems more readable to me.
http://api.rubyonrails.org/classes/Enumerable.html


array.map(&:cash).inject(0, &:+)

or

array.inject(0){|sum,e| sum + e.cash }

#reduce takes a block (the &:+ is a shortcut to create a proc/block that does +). This is one way of doing what you want:

array.reduce(0) { |sum, obj| sum + obj.cash }