ruby · level 2 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A hash can grow, change and shrink as you go.
Put a value at a key with =. If the key is new, the pair is added. If the key is already there, its value is replaced. .delete(:bread) takes a pair out, and .key?(:bread) asks whether a key is there.
Square brackets quietly give nil for a missing key, which can hide mistakes. looks a key up too, but stops with a if it is missing. Give fetch a second argument, a , and it hands that back instead: .fetch(:jam, 0).
stock = { milk: 4, bread: 2 }
stock[:eggs] = 12
stock[:milk] = 5
stock.delete(:bread)
p stock
p stock.key?(:bread)
puts stock.fetch(:jam, 0) Use .fetch when a missing key would be a bug you want to hear about.
guess first
Add one, change one. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
scores = { amy: 3, ben: 5 }
scores[:amy] = scores[:amy] + 2
scores[:cal] = 1
p scores
your turn
Your turn. Restock the corner shop.
Add a new fruit and how many there are. Then fetch a fruit the shop does not stock, with a default of 0.
fix it
The till crashed looking for jam. Can you fix it?
- Read the error. It is a KeyError on line 2. Which key is missing?
- There is no
:jamin the hash, so.fetchstops. You can give it a default to hand back instead. - Change line 2 to jam = stock.fetch(:jam, 0), then press run.
nailed it
your hashes can change their minds. :D
stock[:eggs] = 12adds a pair or replaces a value..deleteremoves a pair and.key?checks for one..fetch(:jam, 0)gives a default when the key is missing.
new words in your collection
- fetch
- default
- KeyError
This lesson isn’t saved. A free account remembers every lesson you finish.