0
0
Rubyprogramming~3 mins

Why Closures and variable binding in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could remember things for you, like a helpful friend?

The Scenario

Imagine you want to create several small tasks that remember different numbers and add them later. You try to write each task by hand, copying and changing the number everywhere.

The Problem

This manual way is slow and easy to mess up. If you forget to change one number, all tasks might add the same wrong number. It's hard to keep track and fix mistakes.

The Solution

Closures let you write one task that remembers its own number automatically. Each task keeps its own memory, so you don't have to copy or change code by hand. This makes your code cleaner and safer.

Before vs After
Before
def make_adder(n)
  return lambda { |x| x + n }
end

add_two = make_adder(2)
add_three = make_adder(3)

puts add_two.call(5)  # 7
puts add_three.call(5) # 8
After
adders = []
[2, 3].each do |n|
  adders << lambda { |x| x + n }
end

puts adders[0].call(5)  # 7
puts adders[1].call(5)  # 8
What It Enables

Closures let you create flexible, reusable pieces of code that remember their own data without extra work.

Real Life Example

Think of a coffee shop where each barista remembers your favorite drink. Closures are like that memory, so each barista (function) serves your special order without asking every time.

Key Takeaways

Manual copying of code for each value is slow and error-prone.

Closures capture and remember variables automatically.

This makes code easier to write, read, and maintain.