×

ruby · level 3 · unit 1 · lesson 4

  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

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.