November 26, 2025
When working with Ruby hashes, we often combine user input with default values. But merge isn’t always ideal — it overwrites existing keys.
That’s where reverse_merge comes in.
What Is reverse_merge?
Unlike Ruby’s merge, Rails’ reverse_merge keeps the original values and only fills in missing ones.
{ a: 1 }.reverse_merge(a: 2)
# => { a: 1 }
Perfect for setting defaults without overwriting what’s already there.
Why It Matters
reverse_merge helps you:
- define clean default configurations
- avoid repetitive conditionals
- make helpers/components more expressive
- keep your code intention clear
Example:
options = params.reverse_merge(page: 1, per_page: 10)
If the value exists, it stays. If not, the default applies. Simple. Explicit. Readable.
A Helpful Mental Model
Think of reverse_merge as:
“Use these defaults unless the caller already provided a value.”
It’s a small method, but it fits beautifully with Rails’ philosophy of clear, intention-driven code.
If this was helpful, let me know — I’m sharing more Ruby/Rails insights soon!




Top comments (0)