这是我的阵列
[{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2
, :alt_amount=>30}]
Run Code Online (Sandbox Code Playgroud)
我想要结果
[{:amount => 30}] or {:amount = 30}
Run Code Online (Sandbox Code Playgroud)
任何的想法?
sep*_*p2k 59
您可以使用inject总和所有金额.然后,如果需要,可以将结果放回哈希值.
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}
Run Code Online (Sandbox Code Playgroud)
San*_*osh 51
Ruby版本> = 2.4.0有一个Enumerable#sum方法.所以你可以做到
arr.sum {|h| h[:amount] }
Run Code Online (Sandbox Code Playgroud)
Jör*_*tag 10
这是一种方法:
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(:+)
Run Code Online (Sandbox Code Playgroud)
但是,我觉得你的对象模型有点缺乏.使用更好的对象模型,您可能会执行以下操作:
a.map(&:amount).reduce(:+)
Run Code Online (Sandbox Code Playgroud)
甚至只是
a.sum
Run Code Online (Sandbox Code Playgroud)
请注意,正如@ sepp2k指出的那样,如果你想要出局Hash,你需要Hash再次将它包装起来.
为什么不拔呢?
ary = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}]
ary.pluck(:amount).sum
# for more reliability
ary.pluck(:amount).compact.sum
Run Code Online (Sandbox Code Playgroud)