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:
Syntax
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
defaults = { color: "blue", size: "medium" }
overrides = { size: "large" }
result = defaults.merge(overrides)
puts result.inspect
puts defaults.inspect # unchanged
Login to try C/C++/Java/PHP code in the editor
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
- Expecting
mergeto changedefaults, when it returns a new hash unless you usemerge!orupdate. - Getting the order wrong, so
overrides.merge(defaults)lets the defaults overwrite your custom values. - 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: