krunal shah krunal shah - 7 months ago 61
Ruby Question

Sum the value of array in hash

This is my array

[{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2
, :alt_amount=>30}]

i want result

[{:amount => 30}] or {:amount = 30}

Any idea?


You can use inject to sum all the amounts. You can then just put the result back into a hash if you need to.

arr = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}]    
amount = arr.inject(0) {|sum, hash| sum + hash[:amount]} #=> 30
{:amount => amount} #=> {:amount => 30}