Today I Learned

hashrocket A Hashrocket project

3 posts by joshuaplicque

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.

CoffeeScript doesn't have a ternary operator

CoffeeScript has no ternary operator! This blew me away, since CoffeeScript is so similar to Ruby.

In Ruby, a ? b : c translates to: Is a true? Ok, then return b, otherwise I’ll return c.

In CoffeeScript, a ? b : c translates to pure madness. If a is not null or "undefined", return a. Otherwise, return an object literal ({ b: c })…!?!

That’s crazy… instead of using a ternary (which doesn’t exist in CoffeeScript), call it a day with:

if a then b else c