与块一起使用时,ruby Hash#merge的行为是什么?

时间:2010-03-05 21:47:42

标签: ruby data-structures hash merge

似乎没有太多记录:

hsh.merge(other_hash){|key, oldval, newval| block} → a_hash

http://ruby-doc.org/core/classes/Hash.html#M002880

1 个答案:

答案 0 :(得分:10)

正如可能预期的那样,生成的哈希将包含块所返回的值,这两个键存在于两个哈希值中:

>> h1 = {:a => 3, :b => 5, :c => 6}
=> {:a=>3, :b=>5, :c=>6}
>> h2 = {:a => 4, :b => 7, :d => 8}
=> {:a=>4, :b=>7, :d=>8}
>> h1.merge h2
=> {:a=>4, :b=>7, :c=>6, :d=>8}
>> h1.merge(h2){|k,v1,v2| v1}
=> {:a=>3, :b=>5, :c=>6, :d=>8}
>> h1.merge(h2){|k,v1,v2| v1+v2}
=> {:a=>7, :b=>12, :c=>6, :d=>8}