The Spaghetti Refactory Established 2015

Merging and reverse merging in Ruby on Rails

I’ve known about merge in Ruby for awhile.

song = { do_you_like: "piña coladas" }
song.merge({ getting_caught: "in the rain" })
# => {
do_you_like: "piña coladas",
getting_caught: "in the rain"
}

But I just found a cool, helpful method that Rails (or specifically, ActiveSupport) adds called reverse_merge.

It does… exactly what it sounds like.

song = { if_you_are_not: "into yoga" }
{ if_you_have: "half a brain" }.reverse_merge(song)
# => {
  if_you_are_not: "into yoga",
  if_you_have: "half a brain"
}

Kinda like Array#unshift.