Lambda behavior

It’s hard for me to understand what makes the following behavior possible (taken from a ruby ​​pickaxe book):

def power_proc_generator value = 1 lambda {value += value} end power_proc = power_proc_generator 3.times {puts power_proc.call} # => 2,4,8 3.times {puts power_proc_generator.call()} # => 2,2,2 

I don’t see how the "power_proc" object allows me to double the value, as I assumed (as if by mistake) that each call will reassign the value to 1.

My question is: why is "3.times {puts power_proc.call}" the result of "2.4.8" rather than "2.2.2"?

+6
source share
2 answers

power_proc_generator returns a lambda that uses (and modifies) the value of a variable in the surrounding area. This is called a closure - the returned function "closes" above the value of the value variable. Therefore, every time you call the returned function, it is multiplied by value by two. The important part is that value stays between calls to power_proc.call , so you are power_proc.call existing variable.

In addition, to clarify the difference between printing power_proc_generator and power_proc.call - power_proc_generator , it calls a new function every time, so you never see the value increase. power_proc.call , on the other hand, continues to call the same function several times.

+5
source

power_proc_generator returns a lambda that includes a closure that contains the value variable. So the variable hangs around from one power_proc.call to another.

+2
source

All Articles