ruby · level 3 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Guards, pins and make patterns smarter.
A adds an if to a pattern: in {total: Integer => total} if total > 100 only fits big orders. A | offers alternatives, so "paid" | "shipped" fits either word. The , ^, compares against a variable you already have, as in {id: ^wanted}, instead of making a new one.
Your own objects can join in. Write deconstruct_keys(keys) to hand back a hash of fields, and hash patterns will match your objects. Data and Struct objects already have it, which is one more reason to use them for values.
Order = Data.define(:id, :total, :status)
def check(order, wanted)
case order
in {id: ^wanted, status: "paid" | "shipped"}
"Order #{wanted} is on its way"
in {total: Integer => total} if total > 100
"Big order needs approval"
else
"Nothing to do"
end
end
puts check(Order.new(id: 7, total: 30, status: "paid"), 7)
puts check(Order.new(id: 8, total: 250, status: "new"), 7)
puts check(Order.new(id: 9, total: 20, status: "new"), 7) Ruby hands deconstruct_keys the keys the pattern asks for, so a careful class can work out only those.
guess first
No pin on expected. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
expected = "Ana"
case { name: "Ben" }
in { name: expected }
puts "Matched #{expected}"
end
puts expected
your turn
Your turn. Let patterns see inside a parcel.
Name the method that hands hash patterns a parcel's fields. Then choose the weight limit for a small parcel. This parcel weighs 2.
fix it
The owner gets the ordinary greeting. Fix the order.
- Ana is an owner, but she gets the ordinary greeting. Which branch does Ruby try first?
- Ruby takes the first pattern that fits, and
{role: String}fits every role. - Move the
"admin" | "owner"branch above theStringone, then press run.
nailed it
you made your patterns sharper. :D
- A guard adds an
if, and|offers alternatives. ^namecompares with a variable instead of capturing a new one.- Write
deconstruct_keysso patterns can match your own objects.
new words in your collection
- guard
- pin
- deconstruct_keys
This lesson isn’t saved. A free account remembers every lesson you finish.