在哈希中求和数组的值

时间:2010-09-16 15:08:52

标签: ruby hash

这是我的数组

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

我想要结果

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

有什么想法吗?

7 个答案:

答案 0 :(得分:58)

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

答案 1 :(得分:56)

您可以使用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}

答案 2 :(得分:43)

Ruby版本> = 2.4.0具有Enumerable#sum方法。所以你可以做到

     $opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=> "x-api-key: hidden"
  )
);
$context = stream_context_create($opts);

$fp = fopen('https://mercury.postlight.com/parser?url=https://www.dev-metal.com/architecture-stackoverflow/','r',false,$context);
$jsonData = stream_get_contents($fp);
$arrayData = json_decode($jsonData,true);
print_r($arrayData);

答案 3 :(得分: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(:+)

但是,我觉得你的对象模型有点缺乏。使用更好的对象模型,您可能会执行以下操作:

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

甚至只是

a.sum

请注意,正如@ sepp2k指出的那样,如果您想要获得Hash,则需要再次将其包装在Hash中。

答案 4 :(得分:3)

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

答案 5 :(得分:0)

为什么不拔毛?

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

答案 6 :(得分:-2)

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