×

ruby · level 3 · unit 6 · 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

case and in check the shape of data and unpack it.

Data from outside, such as a JSON reply, arrives in different shapes. matching checks the shape and pulls out the parts you need in one step. Write case reply, then in branches. Each branch holds a pattern, a description of a shape, and Ruby picks the first one that fits.

in {status: "ok", items: [first, *]} fits a hash whose status is "ok" and whose items hold at least one entry, and it stores that entry in first. Integer => code checks the type, then stores the value in code.

If nothing fits and there is no else, Ruby raises .

def describe(reply)
  case reply
  in {status: "ok", items: [first, *]}
    "First item: #{first}"
  in {status: "ok", items: []}
    "Nothing found"
  in {status: "error", code: Integer => code}
    "Failed with code #{code}"
  end
end
puts describe({ status: "ok", items: ["tea", "jam"] })
puts describe({ status: "ok", items: [] })
puts describe({ status: "error", code: 404 })

A hash pattern only checks the keys you write, so extra keys in the data do no harm.