ruby · level 2 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A looks values up by name, not by number.
An array finds items by their position. A hash finds them by name, like the price list in a café. Each name is a , and each key points to its value. A key and its value together make a .
Write a hash with curly brackets. Inside, put each pair as key => value, with commas between the pairs. The => arrow points from the key to its value.
To look something up, put the key in square brackets: menu["tea"]. Ask for a key that is not there, and you get nil.
menu = { "tea" => 2, "cake" => 3, "soup" => 4 }
puts menu["cake"]
p menu
puts menu.length
p menu["pizza"] p shows the whole hash with its curly brackets, and .length counts the pairs.
guess first
Tea and a scone. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
prices = { "tea" => 2, "scone" => 3 }
puts prices["scone"] + prices["tea"]
your turn
Your turn. Open your own café.
Give each drink a price in whole pounds. Then type one of the three drink names in the last blank to look its price up.
fix it
The menu says nothing about cake. Can you fix it?
- The price is missing from the sentence. What does a hash give back when it cannot find a key?
- It gives back
nil, which shows as nothing. Keys are case-sensitive, so "Cake" and "cake" are different keys. - Change "Cake" inside the square brackets to "cake", then press run.
nailed it
you made your first hash. :D
- A hash stores values under keys, not positions.
- Write each pair as
key => valueinside curly brackets. - A missing key gives back
nil.
new words in your collection
- hash
- key
- pair
This lesson isn’t saved. A free account remembers every lesson you finish.