← Back to Ruby Course | Chapter 5: Hashes | Lesson 4 of 7

merge

In this page:

  1. merge

merge

hash1.merge(hash2) combines two hashes into a new one, with hash2's values overwriting hash1's for any keys they share. merge! performs the same combination but mutates hash1 in place instead of returning a new hash. A block form lets you customize how conflicting keys are resolved instead of just taking the second hash's value.

Note: merge returns a new hash and leaves the original unchanged; merge! (or update) mutates the receiver in place.

Example: merge

markup
defaults = { color: "blue", size: "medium" }
overrides = { size: "large" }

result = defaults.merge(overrides)
puts result.inspect
puts defaults.inspect  # unchanged
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.