×

ruby · level 2 · unit 1 · lesson 3

  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 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.