0
0
RubyConceptBeginner · 3 min read

What is Closure in Ruby: Simple Explanation and Example

In Ruby, a closure is a block, proc, or lambda that captures variables from its surrounding context and keeps them alive even after that context has finished. This means the closure remembers the environment where it was created and can use those variables later.
⚙️

How It Works

A closure in Ruby is like a little box that holds some code and the environment where that code was created. Imagine you write a note and tuck it inside a box along with some objects you want to remember. Even if you move the box somewhere else, the note still knows about those objects inside.

In programming, this means a closure keeps access to variables that were around when it was made, even if the original place where those variables lived is gone. This lets the closure use or change those variables later, which is very useful for things like callbacks or delayed actions.

💻

Example

This example shows a closure capturing a variable from its surrounding scope and using it later.

ruby
def make_counter
  count = 0
  return lambda { count += 1 }
end

counter = make_counter
puts counter.call  # 1
puts counter.call  # 2
puts counter.call  # 3
Output
1 2 3
🎯

When to Use

Use closures in Ruby when you want to keep some data hidden but still accessible to certain code. They are great for:

  • Creating functions that remember state, like counters or accumulators.
  • Passing blocks of code that need to access variables from where they were made.
  • Implementing callbacks or event handlers that run later but still need context.

Closures help keep your code clean and flexible by bundling behavior with its environment.

Key Points

  • A closure is a block, proc, or lambda that remembers its surrounding variables.
  • It keeps variables alive even after the original method or scope ends.
  • Closures allow you to write flexible, stateful code.
  • They are useful for callbacks, delayed execution, and maintaining private state.

Key Takeaways

A closure captures and remembers variables from its creation context.
Closures keep variables alive beyond their original scope.
Use closures to create functions with private, persistent state.
Closures are useful for callbacks and delayed code execution.