How to sum properties of the objects within an array in Ruby
        Posted  
        
            by 
                Ernst Fitschen
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Ernst Fitschen
        
        
        
        Published on 2012-06-30T09:12:24Z
        Indexed on 
            2012/06/30
            9:15 UTC
        
        
        Read the original article
        Hit count: 330
        
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!
© Stack Overflow or respective owner