What if your code could remember things for you, like a helpful friend?
Why Closures and variable binding in Ruby? - Purpose & Use Cases
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.
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.
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.
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
adders = [] [2, 3].each do |n| adders << lambda { |x| x + n } end puts adders[0].call(5) # 7 puts adders[1].call(5) # 8
Closures let you create flexible, reusable pieces of code that remember their own data without extra work.
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.
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.