How to create a closure in Ruby

How to create a closure using Ruby Lambdas

Intro

The following code throws an error because ruby's scoping.

1def outer()
2 foo = 42
3 def inner()
4 puts foo
5 end
6 inner
7end

NameError (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 = 42
3 inner = lambda do
4 puts foo
5 end
6 inner.call
7end

Define the lambda and call it.

If we need to pass it an argument we use the following syntax.

1def outer(x)
2 foo = 42
3 inner = lambda do |x|
4 puts foo, x
5 end
6 inner.call(x)
7end

And finally, if you want to pass a value into your closure, you do the following.

1def outer(y)
2 foo = 42
3 inner = lambda do |x|
4 puts foo + x
5 end
6 inner.call(y)
7end

This 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