【问题标题】:What is the behavior of ruby Hash#merge when used with a blockruby Hash#merge 与块一起使用时的行为是什么
【发布时间】:2011-01-24 07:30:09
【问题描述】:

似乎没有太多记录:

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

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

【问题讨论】:

  • 确实!我已经更改了官方文档。
  • 谢谢你,马克-安德烈。该更改是否已在某处发布?

标签: ruby data-structures hash merge


【解决方案1】:

正如预期的那样,生成的哈希将包含一个块为每个键返回的值,该值存在于被合并的两个哈希中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2023-03-30
    • 2012-05-12
    • 1970-01-01
    • 2017-09-29
    • 2013-09-01
    • 1970-01-01
    相关资源
    最近更新 更多