liveBook · Manning

Merge

As explained in The Well-Grounded Rubyist, Fourth Edition

merge is a Ruby Hash method that returns a new hash containing the receiver's pairs and another hash's pairs, with the other hash's values taking precedence for duplicate keys.

Ruby’s Hash#merge combines two hashes without changing either original. It returns a new hash containing pairs from the receiver and the argument; when both contain the same key, the argument’s value wins. section 9.3.4

Combining overlapping hashes

With h1 = { first: "Joe", last: "Leo", suffix: "III" } and h2 = { suffix: "Jr." }, h3 = h1.merge(h2) produces {:first=>"Joe", :last=>"Leo", :suffix=>"Jr."}. h1 remains unchanged, while h2 supplies the value for the duplicate :suffix key. section 9.3.4

Use the related operations according to whether the original hash should change:

h1 = { first:  "Joe",
       last:   "Leo",
       suffix: "III" }
h2 = { suffix: "Jr." }
h3 = h1.merge(h2)
p h1[:suffix]  #1

Inspect the receiver after merge and compare it with the resulting hash to see nondestructive behavior and duplicate-key precedence. section 9.3.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains returned-hash behavior, duplicate-key precedence, and destructive alternatives, but does not detail implementation internals.
Examples
Uses two hashes containing first, last, and suffix pairs to demonstrate a new result and second-hash precedence.
What it assumes
Assumes familiarity with Ruby hashes, keys, values, and method calls.
What you can do after
Apply merge to create combined hashes without mutating the receiver and predict values for overlapping keys.
How it connects
Connects merge with hashes, key/value pairs, update, merge!, and destructive versus nondestructive operations.

Also explained in

Compare how 5 books explain merge →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.