How to create a closure using Ruby Lambdas
Intro
The following code throws an error because ruby's scoping.
1def outer()2 foo = 423 def inner()4 puts foo5 end6 inner7endNameError (undefined local variable or method 'foo' for main:Object)
To fix it we can use a lambda. We define the lambda using a do/end block.
We then call it with .call.
1def outer()2 foo = 423 inner = lambda do4 puts foo5 end6 inner.call7endDefine the lambda and call it.
If we need to pass it an argument we use the following syntax.
1def outer(x)2 foo = 423 inner = lambda do |x|4 puts foo, x5 end6 inner.call(x)7endAnd finally, if you want to pass a value into your closure, you do the following.
1def outer(y)2 foo = 423 inner = lambda do |x|4 puts foo + x5 end6 inner.call(y)7endThis technique is useful in situations where we want to define functions which have access to variables without having to pass the variables explicitly.
For example, in solving Leetcode problem #200 number of Islands