Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 134 ยท Methods and Blocks

Closures and Binding

Learn how Ruby closures capture variables, what scope gates (def, class, module) do, how to share state with define_method, and how to inspect a Binding object.

In Procs and Lambdas you saw that a lambda "remembers" the variables around it. This lesson explains exactly what it remembers, why a def method cannot see the same variables, and how to get hold of that remembered environment as an object called a Binding.

Scope is one of the places where Ruby differs most from languages such as JavaScript or Python, and one of the places where a small mental model pays off enormously. Once you know that Ruby has only a handful of places where scope is cut off (the scope gates), a whole family of puzzling NameError messages becomes easy to read, and metaprogramming tricks such as define_method with shared state stop feeling like magic.

What a closure captures

A closure captures variables, not values, and it captures the whole local scope that existed where the block was written. If the variable changes later, the closure sees the new value. If the closure changes it, everyone sees the change.

Ruby Shared variables, not copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The lambda and the surrounding code use the same message and counter. Blocks passed to each and times are closures too, which is why counter += n inside a block changes the variable outside.

A fresh variable per call

Each time a scope is entered, its local variables are created anew. A closure made in one call does not share state with a closure from another call.

Ruby Each call makes new variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

a and b each have their own total. This is how you build objects without classes: the lambda is the behavior and the captured variable is the private state. In real code a class is usually clearer, but knowing the closure form helps you read libraries that use it.

Closures created in loops

A block parameter is a new variable on every call of the block, so closures created inside each each get their own. A while loop does not create a new scope, so closures created inside it would share one variable.

Ruby Closures created in loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The each version gives [10, 20, 30]. The while version gives [30, 30, 30] because all three lambdas read the single variable j, which is 3 when they finally run. Prefer each, times and map over while, and the problem never appears. If you must use while, hand the current value to a lambda or method (the third example), because every call of that creates a new value variable. A default argument such as ->(c = j) { } would not help: the default is evaluated when the lambda runs, not when it is created.

Scope gates

Ruby opens a new, empty local scope at exactly three keywords: def, class and module. Variables from outside do not flow in, and ones created inside do not flow out. These are the scope gates. Blocks, lambdas and procs are not gates, which is the whole reason they can be closures.

Ruby def cannot see outside locals (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The error is main.rb:4:in 'Object#check': undefined local variable or method 'limit' for main (NameError). The method body started a fresh scope, so limit is not defined there; Ruby also looked for a method named limit, which explains the wording. The same wall exists around class and module bodies:

Ruby class and module bodies are gates too

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside Plain, secret is nil (not visible), while inner is "local-variable" because it was assigned in that very scope. After the class ends, inner is nil again, and the same holds for x after the module. Rather than fight the gates, use the right tool for sharing:

  • pass the value as an argument;
  • keep it in an instance variable or constant;
  • or flatten the scope (below) with a block.

Flattening the scope with define_method

define_method takes a block, and a block is a closure. So a method defined with define_method can see the variables around it, which def cannot. Rubyists call this flattening the scope.

Ruby define_method keeps the surrounding variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The private prefix is hidden from the rest of the program but available to the method, a poor man's private class variable. The shared count shows the same idea with mutation: both instances increment one counter, because it is a single variable in a scope that outlives every call. This idea returns in define_method and Dynamic Methods.

The same trick works for classes themselves: Class.new { ... } takes a block, so it can capture outer locals, whereas the class keyword cannot.

Ruby Class.new with a block can close over locals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Binding: the environment as an object

A Binding captures the local variables, self and the current method context at a given point. Kernel#binding returns one, and every closure has one (lambda.binding). You can read and write variables through it by name.

Ruby Reading and writing through a Binding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

local_variable_set on a name that does not exist yet creates it, but only inside the binding object; the surrounding code cannot see it, because Ruby decides at parse time which names are local variables. Binding#eval runs a string of code as if it were written at that spot. eval and Binding discusses when this is acceptable, which is rarely. For now treat it as a way to understand what a Binding is.

Bindings travel with closures

Every Proc remembers its Binding. That is how a template engine, a debugger or an irb session can look at variables from a distance.

Ruby Looking inside a closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Even though make_adder has returned, its n and secret live on, because the lambda's binding keeps them alive. Setting n through the binding changed what the lambda does, which proves that the binding refers to the real variables rather than a snapshot.

Reaching into another closure's variables breaks the encapsulation that closures give you. Use it for debugging, teaching and frameworks (ERB templates take a binding), never as your normal way to share data between parts of a program.

Bindings and methods

binding also records self. A binding created inside an instance method exposes that object's instance variables to eval, and one created at top level exposes main.

Ruby self travels with a binding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

source_location reports where the binding was created. It returns the file and the line number, so .last is the line.

Closures and memory

A closure keeps all the variables of its scope alive, not only those it uses. That is convenient, but long-lived callbacks can hold large objects in memory by accident.

Ruby Capture only what you need

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby's block bindings include every local variable of the method, so big_list is still reachable through the lambda's binding, as the last line shows. To really release large data, build the closure in a small helper method that only receives the small values, or set the big variable to nil before returning.

Putting it together: private shared state

Closures give you private state without a class. Here is a tiny rate limiter whose counter nobody can touch:

Ruby A rate limiter made of closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The hash shorthand { allow:, reset: } (Ruby 3.1+) builds { allow: allow, reset: reset }. Both lambdas share one calls, and no other code can name it. A Struct or a class with @calls would be the more conventional choice for a bigger design, but the closure version is complete in six lines.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a closure capture from its surrounding scope?

    Closures share variables with the scope that created them. If either side changes the variable, the other sees it.
  2. 2. Which keywords open a new local scope that cannot see outside local variables?

    def, class and module are the scope gates. Blocks, procs and lambdas are not, which is why they can be closures.
  3. 3. Why can a method created with define_method read a local variable from the class body but a method created with def cannot?

    Using a block instead of def flattens the scope, so the surrounding locals stay visible.
  4. 4. What does binding.local_variable_get(:x) return?

    A Binding holds the local variables, self and context at the point it was created and lets you read them by name.
  5. 5. What are the results of the closures built in while loops that reference the loop variable j and are called after the loop?

    A while loop does not create a new scope per iteration, so all closures share one j. Block parameters of each, map and times are fresh variables per call.

Summary

  • A closure captures variables (not copies) from the scope where it was written; changes are shared both ways.
  • Each call to a method or block creates new local variables, so closures from different calls have independent state.
  • def, class and module are scope gates that hide outer locals; blocks, procs and lambdas are not gates.
  • define_method and Class.new { } flatten the scope by using blocks, so they can see outer locals.
  • A Binding represents locals, self and context; read and write with local_variable_get/set, run strings with eval (see eval and Binding), and get one from a closure with proc.binding.
  • A closure keeps its whole scope alive, which matters for memory when it holds big data.

Next: Enumerators and Lazy Enumerators