Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures in Ruby

Tags:

ruby

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.

like image 966
user413881 Avatar asked Dec 20 '25 22:12

user413881


1 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 "&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.

like image 53
Gazler Avatar answered Dec 24 '25 07:12

Gazler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!