Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Hash#merge
static VALUE
rb_hash_merge(int argc, VALUE *argv, VALUE self)
{
size_t guessed_size = hash_merge_guess_size(argc, argv, self);
VALUE ret = guessed_size ? rb_hash_dup_capa(self, guessed_size) : rb_hash_dup(self);
return rb_hash_update(argc, argv, copy_compare_by_id(ret, self));
}
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:
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
selfandother_hash. -
The block’s return value becomes the new value for the entry in
self.
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.