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

Spike Fitsch picture Spike Fitsch · Jun 30, 2012 · Viewed 37.6k times · Source

I understand that in order to sum array elements in Ruby one can use the inject method, i.e.

array = [1,2,3,4,5];
puts array.inject(0, &:+) 

But how do I sum the properties of objects within an object array e.g.?

There's an array of objects and each object has a property "cash" for example. So I want to sum their cash balances into one total. Something like...

array.cash.inject(0, &:+) # (but this doesn't work)

I realise I could probably make a new array composed only of the property cash and sum this, but I'm looking for a cleaner method if possible!

Answer

Yuri  Barbashov picture Yuri Barbashov · Jun 30, 2012
array.map(&:cash).inject(0, &:+)

or

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