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

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


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

or

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


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


#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 }