Episode 21a - Idiomatic Ruby: Hashes With Symbols

Because symbols are often used with hashes, there's a shortcut syntax in Ruby for defining such a hash. Instead of writing this:

person = {:name => "Dana", :email => "dana@email.com"}
puts person[:name] # the output is Dana

You can write this:

person = {name: "Dana", email: "dana@email.com"}
puts person[:name] # the output is Dana

Here the => is gone and the colon for the symbol moves to the end of the word. Note that this shortcut is nice since it takes fewer characters to write, but it can be misleading. The shortcut can only be used when the keys are symbols. Also, when accessing values from the hash, the colon for the symbol is still at the start of the word, it doesn't change.

Exercises:

  1. Identify and fix the error in the following code.
    food = {name: "Lettuce", color: "green"}
    puts food[name:]
  2. Convert the following hashes to use symbols as the keys with the shortcut syntax.
    grades = { "Jane Doe" => 10, "Jim Doe" => 6 }
    puts grades["Jim Doe"] # the output is 6
    
    options = { :font_size => 10, :font_family => "Arial" }
    puts options[:font_size] # the output is 10
    
    h = {"colors"  => ["red", "blue", "green"], "letters" => ["a", "b", "c" ]}
    p h["letters"] # the output is ["a", "b", "c"]