在hash中求和数组的值 [英] Sum the value of array in hash

查看:130
本文介绍了在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}

任何想法?

推荐答案

您可以使用 inject 来总和所有金额。如果需要的话,你可以把结果放回散列。

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}

这篇关于在hash中求和数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆