Sum the value of array in hash

This is one way to do it:

a = {amount:10,gl_acct_id:1,alt_amount:20},{amount:20,gl_acct_id:2,alt_amount:30}
a.map {|h| h[:amount] }.reduce(:+)

However, I get the feeling that your object model is somewhat lacking. With a better object model, you would probably be able to do something like:

a.map(&:amount).reduce(:+)

Or even just

a.sum

Note that as @sepp2k pointed out, if you want to get out a Hash, you need to wrap it in a Hash again.


Ruby versions >= 2.4.0 has an Enumerable#sum method. So you can do

arr.sum {|h| h[:amount] }

array.map { |h| h[:amount] }.sum


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}

Tags:

Ruby

Hash