Ruby for Instance / Closures

# Define a closure that captures a local variable from the outer scope
def adder
  x = 10
  ->(y) { x + y }
end

# Define a closure that captures a local variable and modifies it
def counter
  n = 0
  -> { n += 1 }
end

# Define a closure that captures multiple local variables
def greeter
  name = "Alice"
  age = 20
  -> { "Hello, #{name} (#{age})" }
end

Try on playground

Next: recursion

made with by dfxe / source / license