Sum the value of array in hash

2019-01-17 18:56发布

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?

标签: ruby hash
6条回答
走好不送
2楼-- · 2019-01-17 19:41

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}
查看更多
Juvenile、少年°
3楼-- · 2019-01-17 19:48

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

arr.sum {|h| h[:amount] }
查看更多
男人必须洒脱
4楼-- · 2019-01-17 19:50
[{
    :amount=>10,
    :gl_acct_id=>1,
    :alt_amount=>20
},{
    :amount=>20,
    :gl_acct_id=>2,
    :alt_amount=>30
}].sum { |t| t[:amount] }
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-17 19:55

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

查看更多
Rolldiameter
6楼-- · 2019-01-17 19:56

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.

查看更多
forever°为你锁心
7楼-- · 2019-01-17 19:59
total=0
arr = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}]
arr.each {|x| total=total+x[:amount]}
puts total
查看更多
登录 后发表回答