ruby · level 3 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A remembers the variables around it.
A block can see variables from the lines around it. That is why a running total works inside each. Wrap that block in a lambda and it keeps those variables, even after the method that made them has finished. That is a closure: code plus its memories.
Every variable lives in a , the area where its name means something. A def starts a fresh scope, so a method cannot see variables from outside. A block does not, so it can. Here each ticket machine keeps its own private number.
def ticket_machine(prefix)
number = 0
lambda do
number += 1
"#{prefix}-#{number}"
end
end
deli = ticket_machine("D")
bakery = ticket_machine("B")
puts deli.call
puts deli.call
puts bakery.call number += 1 is a short way to write number = number + 1.
guess first
A lambda and a method both use greeting. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
greeting = "Hiya"
shout = -> { puts greeting.upcase }
def whisper
puts greeting.downcase
end
shout.call
whisper
your turn
Your turn. Build a card with a spending limit.
Pick a limit and two prices so the first purchase goes through and the second one is refused. The closure remembers what has been spent.
fix it
The visitor counter crashes on the first visitor. Fix it.
- Inside the method,
visitorsisnil. Why can the method not see the 0 on line 1? defstarts a fresh scope. A lambda is a closure, so it can seevisitors.- Make line 2
welcome = lambda do |name|, then call it withwelcome.call("Ana")andwelcome.call("Ben").
nailed it
you built closures that remember. :D
- A closure keeps the variables from where it was made.
defstarts a fresh scope. Blocks and lambdas do not.- Each closure from a maker method keeps its own private state.
new words in your collection
- closure
- scope
This lesson isn’t saved. A free account remembers every lesson you finish.