To be honest, I was always confused by name: and :name in Ruby. I never fully understood the differences until I read about it in the Hartl Tutorial.
The Michael Hartl Ruby on Rails Tutorial is an
excellent way to learn Ruby on Rails. The tutorial
has been updated to Ruby 2.0 and Rails 4.0. I've been working through this tutorial to
get updated on the new features and differences in Rails 4.0.
There are several ways to define elements in a hash using a literal representation of key value pairs. We are going to define a hash called pairings that will pair a coffee with a dessert that goes well with this coffee. We will use 3 different ways to assign the key value pairs.
1. Using a string and a hashrocket. The "=>" is called the hashrocket because doesn't it look like one?
pairings = { "coffee" => "Columbian", "dessert" => "Flan" }
Use the string as a key in pairings["coffee"] to access the value "Columbian"
2. Using a symbol for the key and a hashrocket. In the previous example the key was the string "coffee". We will replace this string with the symbol :coffee. A symbol is a string without the extra baggage. Ruby will create an almost unlimited number of string instances for all your hash keys, but will only keep one copy of a symbol in memory at a time.
pairings = { :coffee => "Columbian", :dessert => "Flan" }
Use the symbol as the key in pairings[:coffee] to access the value "Columbian"
3. "Good Guy" Ruby let's us replace the ":symbol =>" with just 'symbol:'. I kinda miss the hashrocket
but I don't miss typing all those extra characters.
pairings = { coffee: "Columbian", dessert: "Flan"}
Use the symbol as the key in pairings[:coffee] to access the value "Columbian"
Easy peasy... the name: syntax simplifies hash construction.
TL;DR Use coffee: to replace ":coffee => " or " 'coffee' => " when creating key value pairs for hashes.