Contact: aviboots(AT)netvision.net.il
41,522 questions
54,123 answers
573 users
# A lambda that captures x and y from the surrounding scope. x = 10 y = 20 add = -> { x + y } # closure created here result = add.call puts result =begin run: 30 =end
# Closures capture variables by reference counter = 0 inc = -> { counter += 1 } # closure captures counter inc.call inc.call puts counter =begin run: 2 =end
# Closures with parameters factor = 3 multiply = ->(a, b) { (a + b) * factor } # captures factor puts multiply.call(5, 5) =begin run: 30 =end
# Using a block as a closure def apply_twice yield yield end x = 10 apply_twice { puts x } # block captures x =begin run: 10 10 =end
# Using Proc.new x = 7 printer = Proc.new { puts x } # captures x printer.call =begin run: 7 =end