0
0
Rubyprogramming~5 mins

Closures and variable binding in Ruby

Choose your learning style9 modes available
Introduction
Closures let you keep a little piece of code and the variables it uses together, so you can use them later even outside their original place.
When you want to remember some settings or values inside a small piece of code to use later.
When you create a function inside another function and want the inner one to use variables from the outer one.
When you want to make a custom action that keeps some information hidden but still works when called.
When you want to delay running some code but keep the current values it needs.
Syntax
Ruby
def outer_function
  x = 10
  inner_function = -> { puts x }
  inner_function
end

closure = outer_function
closure.call
The inner function (closure) remembers the variable x from the outer function.
In Ruby, closures can be created with lambdas (->) or blocks.
Examples
This creates a closure that remembers the message 'Hello!' and prints it when called.
Ruby
def make_printer(msg)
  -> { puts msg }
end

printer = make_printer("Hello!")
printer.call
The closure remembers and updates the count variable each time it is called.
Ruby
def counter
  count = 0
  -> { count += 1 }
end

c = counter()
puts c.call
puts c.call
The closure uses the current value of x when called, showing variable binding at call time.
Ruby
x = 5
closure = -> { puts x }
x = 10
closure.call
Sample Program
This program creates a closure that remembers the greeting message for 'Alice' and prints it when called.
Ruby
def greeting_maker(name)
  greeting = "Hello, #{name}!"
  -> { puts greeting }
end

say_hello = greeting_maker("Alice")
say_hello.call
OutputSuccess
Important Notes
Closures keep variables alive even after the outer function finishes.
Changing a variable outside after creating a closure may or may not affect the closure depending on when the variable is accessed.
Closures are useful for creating functions with memory or delayed actions.
Summary
Closures are functions that remember variables from where they were made.
They let you keep data hidden but usable later.
In Ruby, closures are often made with lambdas or blocks.