🚀 Understanding reverse_merge in Ruby on Rails

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?

Article content

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.


Bring Your Next Project to Life with High-Quality Development

Don’t miss the opportunity to take your project to the next level. Whether you want to launch something new or improve an existing platform, we build maintainable, scalable software that empowers your business.

Get in touch — Start your project 🚀 Available for freelance and team-based projects • Fast replies

đź’ˇ 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! 💬🔥

One thought on “🚀 Understanding reverse_merge in Ruby on Rails

  1. Only a small addition: reverse_merge has an alias, which makes it’s Intention even more understandable – with_defaults. Example from above reads then

    options = params.with_defaults(page: 1, per_page: 10)

Leave a comment