当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Hash.merge用法及代码示例


本文简要介绍ruby语言中 Hash.merge 的用法。

用法

merge → copy_of_self
merge(*other_hashes) → new_hash
merge(*other_hashes) { |key, old_value, new_value| ... } → new_hash

返回通过将每个 other_hashes 合并到 self 的副本中形成的新哈希。

other_hashes 中的每个参数都必须是一个哈希。

带参数且无块:

  • 返回通过将 other_hashes 中的每个连续 Hash 合并到 self 中形成的新 Hash 对象。

  • 每个new-key 条目都添加到末尾。

  • 每个 duplicate-key 条目的值都会覆盖前一个值。

例子:

h = {foo: 0, bar: 1, baz: 2}
h1 = {bat: 3, bar: 4}
h2 = {bam: 5, bat:6}
h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}

带参数和块:

  • 返回一个新的 Hash 对象,它是 self 和每个给定哈希的合并。

  • 给定的哈希从左到右合并。

  • 每个new-key 条目都添加到末尾。

  • 对于每个重复键:

    • 使用键和旧值和新值调用块。

    • 块的返回值成为条目的新值。

例子:

h = {foo: 0, bar: 1, baz: 2}
h1 = {bat: 3, bar: 4}
h2 = {bam: 5, bat:6}
h3 = h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}

没有参数:

  • 返回 self 的副本。

  • 该块(如果给定)将被忽略。

例子:

h = {foo: 0, bar: 1, baz: 2}
h.merge # => {:foo=>0, :bar=>1, :baz=>2}
h1 = h.merge { |key, old_value, new_value| raise 'Cannot happen' }
h1 # => {:foo=>0, :bar=>1, :baz=>2}

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Hash.merge。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。