merge returns a new hash and leaves the original unchanged, while merge! is destructive, which means it changes the hash you call it on.
Both combine the key-value pairs of the two hashes. When a key exists in both, the value from the argument wins, so :b becomes 3 below. A block, if you pass one, runs only for those shared keys and picks the value, as in h1.merge(h2) { |key, old, new| old + new }.
Use merge when other code still needs the original hash. Use merge! when you own the hash and want to avoid building a copy. The trailing ! is Ruby's convention for the version that changes the object, and update is another name for merge!.
h1 = { a: 1, b: 2 }
h2 = { b: 3, c: 4 }
h1.merge(h2) # Returns { a: 1, b: 3, c: 4 }, h1 unchanged
h1.merge!(h2) # h1 is now { a: 1, b: 3, c: 4 }
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓