Sample code:
def func(a, &closure)
return a if a
closure ||= lambda{ |words| puts "!!! " + words }
closure.call("1")
closure.call("2")
end
func(false){ |words| puts "??? " + words }
Please explain. I can not understand this line:
closure ||= lambda{ |words| puts "!!! " + words }
If you remove || will be permanently displayed as follows: "!!! 1", "!!! 2". Why?
And also explain this:
def func(a, &closure)
where did &closure.
def func(a, &closure)
return a if a
closure ||= lambda{ |words| puts "!!! " + words }
closure.call("1")
closure.call("2")
end
func(false){ |words| puts "??? " + words }
In "&closure" the ampersand (&) means that the function takes a block as a parameter. What is happening is you are passing a Proc (a block is just a Proc defined with a different syntax) to the func function which is then called with the variable 1 and 2.
The ||= means "or equals." It is used to assign a value to a variable if the current value is nil. It is shorthand for:
closure = lamda{ |words| puts "!!! " + words } if closure.nil
This blog post explains blocks, Procs and lamdas well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With