×

ruby · level 2 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a name tag that starts with a colon.

Most Ruby hashes use symbols as keys. A symbol is a fixed name tag with a colon in front, like :milk. It is not a string: you never change a symbol, you only use it as a label.

Symbol keys have a shorthand. Write milk: 4 instead of :milk => 4. The colon moves to the end and the arrow disappears. To look a value up, the colon goes back to the front: stock[:milk].

Careful: :milk and "milk" are different keys. Ask for the wrong one and you get nil.

stock = { milk: 4, bread: 2, eggs: 12 }
puts stock[:eggs]
p stock
p stock["eggs"]
p :eggs.class

p shows symbol keys in the same shorthand you wrote them in.