clouser with simple example
Closures in Ruby refer to the ability of a block of code to retain access to variables and the surrounding context in which it was defined, even when it is executed in a different scope or context. Closures are a fundamental aspect of Ruby's blocks and lambdas.
Here's an example that demonstrates closures in Ruby:
def create_multiplier(factor)
lambda do |number|
number * factor
end
end
double = create_multiplier(2)
triple = create_multiplier(3)
puts double.call(5) # Output: 10
puts triple.call(5) # Output: 15
In this example, the create_multiplier
method returns a lambda that multiplies a given number by the factor
argument passed to create_multiplier
. The lambda captures and retains the value of factor
even after the create_multiplier
method has finished executing. This is the essence of closures.
When we invoke create_multiplier(2)
, it returns a lambda that multiplies a number by 2. We assign this lambda to the variable double
. Similarly, create_multiplier(3)
returns a lambda that multiplies a number by 3, assigned to triple
.
Later, when we call double.call(5)
, the lambda captures and uses the retained value of factor
(which is 2) and multiplies it by 5, resulting in the output of 10. Similarly, calling triple.call(5)
multiplies 5 by the retained value of factor
(which is 3), resulting in the output of 15.
The important aspect here is that the lambdas created by create_multiplier
retain access to the factor
variable in the surrounding scope, forming a closure. This allows the lambdas to "remember" and use the value of factor
even when they are executed in a different scope or context.
Closures are powerful constructs in Ruby as they enable the creation of flexible and reusable blocks of code that can operate on captured values from their surrounding environment. They are commonly used in scenarios like callback functions, memoization, and functional programming paradigms.
Last updated