What is Closure in Ruby: Simple Explanation and Example
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.
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
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.