1. Closure Closure is block of code/function/method that has two properties:
- It can be passed around like an object (to be called later).
- It remembers the values of all the variables that were in scope when the function was created, then it is able to access those variables when it is called.
Proc & Lambda are closure.
2. Proc (Procedure)
Proc is a closure and an object that can be bound to a variable and reused.
default proc
12
p=Proc.new{puts"Hello Rubyist"}p.call# prints Hello Rubyist
proc with parameter
12
p=Proc.new{|a,b|puts"x: #{a}, y: #{b}"}p.call(1,2)# prints x: 1, y: 2
defto_do(p)p.callendp=Proc.new{puts"proc"}to_do(p)# prints proc
proc as closure
123456789101112
defto_do(proc1,proc2)proc1.callproc2.callenda=Proc.new{puts"first proc"}b=Proc.new{puts"second proc"}to_do(a,b)# prints# first proc# second proc
3. Lambda
Lambdas are a more strict form of Proc, something like:
- Lambda are more strict with regard to argument checking.
- Lambdas can return a value with the return keyword.
default lambda
12
l=lambda{puts"Hello Rubyist"}l.call# prints "Hello Rubyist"
lambda with parameter
12
l=lambda{|a,b|puts"x: #{a}, y: #{b}"}l.call(1,2)# prints x: 1, y: 2