ruby · level 2 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Strings or symbols? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
pet = { name: "Biscuit", legs: 4 }
p pet["name"]
puts pet[:legs]
your turn
Your turn. Describe your dream pet.
Fill in the pet's name, what kind of animal it is and how many legs it has, then press run.
fix it
The shop says it has no eggs. Can you fix it?
- The number is missing, so the lookup found nothing. Look closely at how the keys are written on line 1.
- Line 1 uses string keys, but line 2 asks for the symbol
:eggs. They are different keys. - Change line 1 to stock = { milk: 4, eggs: 12 }, then press run.
nailed it
your keys have name tags now. :D
- A symbol is a name tag with a colon, like
:milk. milk: 4is shorthand for:milk => 4.:milkand"milk"are different keys.
new words in your collection
- symbol
This lesson isn’t saved. A free account remembers every lesson you finish.