Sum 2使用相同的键散列属性

问题描述 投票:40回答:2

我有2个哈希,例如:

{'a' => 30, 'b' => 14}
{'a' => 4, 'b' => 23, 'c' => 7}

其中abc是对象。我怎样才能将这些哈希的密钥加起来得到一个新的哈希:

{'a' => 34, 'b' => 37, 'c' => 7}
ruby hash attributes sum
2个回答
75
投票
a_hash = {'a' => 30, 'b' => 14}
b_hash = {'a' => 4, 'b' => 23, 'c' => 7}

a_hash.merge(b_hash){ |k, a_value, b_value| a_value + b_value }
=> {"a"=>34, "b"=>37, "c"=>7}

b_hash.merge(a_hash){ |k, b_value, a_value| a_value + b_value }
=> {"a"=>34, "b"=>37, "c"=>7}

1
投票

如果某人希望添加2个以上的哈希值,请使用此功能

#sample array with any number of hashes
sample_arr =  [{:a=>2, :b=>4, :c=>8, :d=>20, :e=>5},
{:a=>1, :b=>2, :c=>4, :d=>10, :e=>5, :r=>7},
{:a=>1, :b=>2, :c=>4, :d=>10},
{:a=>2, :b=>4, :c=>8, :d=>20, :e=>5},
{:a=>1, :b=>2, :c=>4, :d=>10, :e=>5, :r=>7},
{:a=>1, :b=>2, :c=>4, :d=>10}]

sample_arr.inject { |acc, next_obj| acc.merge(next_obj) { |key,arg1,arg2| arg1+agr2 } }`

在异构散列的情况下(包含字符串和数字)。仅用于添加整数。

@resultant_visit_hash = arr.inject { |acc, next_obj| acc.merge(next_obj) { |key,arg1,arg2| arg1+agr2 if (arg1.class == Fixnum && arg2.class == Fixnum) } } 

代码是自我解释的。

© www.soinside.com 2019 - 2024. All rights reserved.