0
0
RubyHow-ToBeginner · 3 min read

How to Merge Two Hashes in Ruby: Simple Guide

In Ruby, you can merge two hashes using the merge method, which returns a new hash combining keys and values from both. To update the original hash, use merge! which modifies it in place.
📐

Syntax

The merge method combines two hashes and returns a new hash without changing the originals. The merge! method updates the original hash with the contents of another.

  • hash1.merge(hash2) - returns a new hash with combined keys and values.
  • hash1.merge!(hash2) - modifies hash1 by adding keys and values from hash2.
ruby
hash1.merge(hash2)
hash1.merge!(hash2)
💻

Example

This example shows how to merge two hashes using both merge and merge!. It demonstrates that merge returns a new hash, while merge! changes the original.

ruby
hash1 = { a: 1, b: 2 }
hash2 = { b: 3, c: 4 }

# Using merge (non-destructive)
merged_hash = hash1.merge(hash2)
puts "Merged hash: #{merged_hash}"
puts "Original hash1 after merge: #{hash1}"

# Using merge! (destructive)
hash1.merge!(hash2)
puts "Hash1 after merge!: #{hash1}"
Output
Merged hash: {:a=>1, :b=>3, :c=>4} Original hash1 after merge: {:a=>1, :b=>2} Hash1 after merge!: {:a=>1, :b=>3, :c=>4}
⚠️

Common Pitfalls

One common mistake is expecting merge to change the original hash, but it returns a new hash instead. Another is not knowing how conflicts are handled: keys present in both hashes will have their values overwritten by the second hash.

ruby
hash1 = { x: 10, y: 20 }
hash2 = { y: 30, z: 40 }

# Wrong: expecting hash1 to change
hash1.merge(hash2)
puts hash1 # Still {:x=>10, :y=>20}

# Right: use merge! to update hash1
hash1.merge!(hash2)
puts hash1 # Now {:x=>10, :y=>30, :z=>40}
Output
{:x=>10, :y=>20} {:x=>10, :y=>30, :z=>40}
📊

Quick Reference

MethodDescriptionModifies Original?
mergeReturns a new hash combining two hashesNo
merge!Updates the original hash with another hashYes

Key Takeaways

Use merge to combine hashes without changing originals.
Use merge! to update the original hash with new keys and values.
When keys overlap, values from the second hash overwrite the first.
Remember merge returns a new hash; it does not modify in place.
Choose the method based on whether you want to keep or change the original hash.