Method: Hash#merge

Defined in:
hash.c

#mergeObject #merge(*other_hashes) ⇒ Object #merge(*other_hashes) {|key, old_value, new_value| ... } ⇒ Object

Returns the new Hash formed by merging each of other_hashes into a copy of self.

Each argument in other_hashes must be a Hash.


With arguments and no block:

  • Returns the new Hash object formed by merging each successive Hash in other_hashes into self.

  • Each new-key entry is added at the end.

  • Each duplicate-key entry’s value overwrites the previous value.

Example:

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}

With arguments and a block:

  • Returns a new Hash object that is the merge of self and each given hash.

  • The given hashes are merged left to right.

  • Each new-key entry is added at the end.

  • For each duplicate key:

    • Calls the block with the key and the old and new values.

    • The block’s return value becomes the new value for the entry.

Example:

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}

With no arguments:

  • Returns a copy of self.

  • The block, if given, is ignored.

Example:

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}

Overloads:

  • #merge(*other_hashes) {|key, old_value, new_value| ... } ⇒ Object

    Yields:

    • (key, old_value, new_value)


4124
4125
4126
4127
4128
# File 'hash.c', line 4124

static VALUE
rb_hash_merge(int argc, VALUE *argv, VALUE self)
{
    return rb_hash_update(argc, argv, rb_hash_dup(self));
}