开发者

What is the behavior of ruby Hash#merge when used with a block

开发者 https://www.devze.com 2022-12-22 05:42 出处:网络
It does not seem to be documented very much: hsh.merge(other_hash){|key, oldval, newval| block} → a_hash

It does not seem to be documented very much:

hsh.merge(other_hash){|key, oldval, newval| block} → a_hash
开发者_如何学编程

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


As it might be expected, the resulting hash will contain the value returned by a block for every key which exists in both hashes being merged:

>> 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}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号