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:
- Use merge for a new combined hash. section 9.3.4
- Use update when the receiver should absorb the other hash’s pairs in place. section 9.3.4
- Use merge! as a synonym for update. section 9.3.4
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




