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

merge

merge combines two hashes into one, like joining two contact lists. If both have the same key, the second one's value wins.

In this page:

  1. merge
Syntax
ruby
combined = hash1.merge(hash2)
combined = hash1.merge(hash2) { |key, old, new| old + new }

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting merge to change defaults, when it returns a new hash unless you use merge! or update.
  2. Getting the order wrong, so overrides.merge(defaults) lets the defaults overwrite your custom values.
  3. Merging hashes that use string keys and symbol keys, so the same setting appears twice.
🔒

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.