Ruby 1.9 and the new hash syntax

Wednesday, August 3rd 2011 at 6:57pm

I knew that Ruby 1.9 added a new syntax for hashes, I just never seem to start using it, because the old one is baked in so hard.

The old one, we’re all familiar with is:

new_hash = {:simon => "Talek", :lorem => "Ipsum"}

This is all nice and dandy, but it could be simpler and cleaner. Check out the Ruby 1.9 style, it sort of resembles JSON:

new_hash = {simon: "Talek", lorem: "Ipsum"}

But now you look closer and ask, “But previously the key was a symbol explicitly, what’s with this now?”.

Well you’re right, the new notation is sort of a syntactic sugar for the most common style of hashes out there, the so called symbol to object hash. If you do this in the irb, you’ll see ruby returning the old school hash, with the symbols used as keys:

> new_hash = {simon: "Talek", lorem: "Ipsum"}
=> {:simon=>"Talek", :lorem=>"Ipsum"} 

If you need to have arbitrary objects as your hash keys, you’ll still have to do it old school.

If you've enjoyed this, you should follow me on Twitter.
To read more, head over to break the bit.

Tagged with: