ruby · level 3 · 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 is a proc with strict rules.
Write a lambda with an arrow: ->(weight, zone) { weight * zone }, or with lambda do |weight, zone| for longer ones. Like a proc, you keep it in a variable and run it with .call. Unlike a proc, a lambda is strict about its , the number of arguments it expects.
Give a lambda the wrong number and it raises . A proc shrugs instead: a missing argument becomes nil and extras are dropped. That silence hides bugs, so professionals reach for lambdas when they store a rule or a calculation in a variable.
A lambda also treats return like a method does: it leaves the lambda only, and the code around it carries on.
shipping = ->(weight, zone) { weight * zone }
loose = proc { |weight, zone| [weight, zone] }
puts shipping.call(2, 3)
puts shipping.arity
p loose.call(2) A proc's return tries to leave the whole method around it, which surprises people, so lambdas are the safer choice.
guess first
A return inside a lambda. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def shop_status
status = lambda do |count|
return "sold out" if count == 0
"in stock"
end
result = status.call(0)
"Shop says: #{result}"
end
puts shop_status
your turn
Your turn. Store a password rule in a lambda.
Pick a minimum password length from 4 to 11 and type it in the blank. The first password should pass, the second should fail.
fix it
Each room's floor area should print. Fix the call.
- Read the error: how many arguments did
areaget, and how many does it want? - Each room is one array. A lambda will not split it into two numbers for you.
- Pass both numbers on line 4:
area.call(room[0], room[1]).
nailed it
you made lambdas keep to the rules. :D
->(x) { }makes a lambda, and.callruns it.- The wrong arity raises ArgumentError instead of guessing quietly.
returninside a lambda leaves only the lambda.
new words in your collection
- lambda
- arity
- ArgumentError
This lesson isn’t saved. A free account remembers every lesson you finish.