我有2个哈希,例如:
{'a' => 30, 'b' => 14}
{'a' => 4, 'b' => 23, 'c' => 7}
其中
a
,b
和c
是对象。我如何总结这些哈希的键,以获得一个新的哈希,像:{'a' => 34, 'b' => 37, 'c' => 7}
最佳答案
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}
关于ruby - 用相同的键求和2哈希属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4091487/