Today I Learned

hashrocket A Hashrocket project

Yo dawg, I heard you like Hash#merge

Yo dawg...I heard you like Hash#merge...

With #reverse_merge, you can have a new hash in your old hash, and keep the keys from your old hash in your new hash.

hash_one = { a: 1, b:2 }
hash_one.merge({ a:2, b:3 }) # => { a:2, b:3 } 

So the hash supplied as a parameter will override hash_one's keys and values.

If you're in Rails and you don't want your existing hash keys to get overwritten, use your new friend #reverse_merge

Now, you can merge the other way around!

hash_one = { a: 1, b:2 }
hash_one.reverse_merge({ a:2, b:3, c:3 }) # => { a:1, b:2, c:3 } 

Boom, keep your keys.

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.