ruby · level 3 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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. 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.
guess first
Three commands for a text adventure. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def move(command)
case command
in ["go", direction]
"Walking #{direction}"
in ["take", item, *rest]
"Taking #{item} and #{rest.length} more"
in []
"Say something!"
end
end
puts move(["take", "lamp", "key", "map"])
puts move(["go", "north"])
puts move(["dance"])
your turn
Your turn. Teach the forecast about rain.
Fill the first blank so the second branch matches a rainy reply. Then choose a chance of rain, from 0 to 100, in the last blank.
fix it
Ana is an admin, but the pattern never fits. Fix it.
- The reply looks right, yet it falls through to
else. Look at the keysJSON.parsegives you. JSON.parsemakes string keys like "user", but hash patterns only match symbol keys.- Add
symbolize_names: trueto theJSON.parsecall on line 2, then press run.
nailed it
you took data apart with patterns. :D
caseandinpick the first pattern the data fits.- Patterns unpack values into variables as they match.
- Add an
else, or unmatched data raises NoMatchingPatternError.
new words in your collection
- pattern matching
- pattern
- NoMatchingPatternError
This lesson isn’t saved. A free account remembers every lesson you finish.