Closing in Ruby

Code example:

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 }   

Explain, please. I can not understand this line:

closure ||= lambda{ |words| puts "!!! " + words }

If you remove ||will be permanently displayed in the following way: "!!! 1", "!!! 2". What for? And also explain this:

def func(a, &closure)

where &closure.

+3
source share
3 answers
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 "& close", an ampersand (&) means that the function takes a block as a parameter. What happens is you pass Proc (a block is just Proc defined with a different syntax) to the func function, which is then called using variables 1 and 2.

Value || = means "or equal." It is used to assign a value to a variable if the current value is zero. This is a shorthand for:

closure = lamda{ |words| puts "!!! " + words } if closure.nil

This blog post explains blocks Procs and lamdas well.

+4

closure . , . func , closure . , nil. ||= , nil, , . , func , closure ; , closure lambda{...}. , ||= =, closure lambda{...} , . closure.call(1) 1 words closure, !!!1; closure.call(2), !!!2.

+1

closure ||= lambda{ |words| puts "!!! " + words }

|| , , ambda {| words | puts "!!!" + words}

func(false){ |words| puts "??? " + words } 

default lambda (!!!)

||, lambda

You can print !!! without deleting || just call

   func(false)
+1
source

All Articles