Rails hash confusion

13 Mar

One of the things that confused and intimidated me when first encountering Rails (I’m a newbie, so we’re talking 3.2 here) was the preponderance of colons ‘:’ and their seemingly ever-shifting whereabouts.

:controller (sometimes on the left)
controller: (sometimes on the right)

While it may seem silly to some, these little seeming inconsistencies, taken at a gulp while perusing a page of code, made my eyes blur and led me to quickly conclude that whatever voodoo it was that some folks were in command of to understand so many tiny details and nuances of syntax, I didn’t understand it a bit.

I did understand the idea of a Ruby symbol:


And I understood the idea of a hash:

{ :cats => "animal" }

But nowhere in Ruby had I seen a colon on the right!

Cutting to the chase:

Turns out it’s just an update in Rails that gives developers a short-hand alternative for writing hashes. They probably find it difficult to imagine how anyone could be anything but dazzled at the newfound convenience!

:controller => :posts
:cats => "Frisky"


controller: :posts
cats: "Frisky"

…are the exact same thing in later versions of Rails. Colon to the left with a hashrocket ( => ), or to the right without. That’s it.

A convenience for those already familiar with Rails conventions, but a possible point of confusion for newbies trying to parse out the syntax.


Comments are welcome!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: