Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Hash#merge

[A, B] (*::hash[A, B] other_hashes) -> ::Hash[A | K, B | V]
[A, B, C] (*::hash[A, B] other_hashes) { (K key, V oldval, B newval) -> C } -> ::Hash[A | K, B | V | C]
merge(*other_hashes) → new_hash
merge(*other_hashes) { |key, old_value, new_value| ... } → new_hash

Each argument other_hash in other_hashes must be a hash.

With arguments other_hashes given and no block, returns the new hash formed by merging each successive other_hash into a copy of self; returns that copy; for each successive entry in other_hash:

  • For a new key, the entry is added at the end of self.

  • For duplicate key, the entry overwrites the entry in self, whose position is unchanged.

Example:

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 other_hashes and a block given, behaves as above except that for a duplicate key the overwriting entry takes it value not from the entry in other_hash, but instead from the block:

  • The block is called with the duplicate key and the values from both self and other_hash.

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

Example:

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

With no arguments, returns a copy of self; the block, if given, is ignored.

Related: see Methods for Assigning.

See also #merge! #member? #length #rassoc also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0