我有2个哈希,例如:
{'a' => 30, 'b' => 14}
{'a' => 4, 'b' => 23, 'c' => 7}
其中a
,b
和c
是对象。我如何总结这些哈希的密钥以获得新的哈希:
{'a' => 34, 'b' => 37, 'c' => 7}
答案 0 :(得分: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)
如果有人希望添加两个以上的哈希,请使用此
const docs
对于异构哈希(包含字符串和数字)。仅用于添加整数。
#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 } }`
代码不言自明。