Top Level Binding

In case you have wondered, what this top-level constant TOPLEVEL_BINDING is all about:

It is, as its name suggest, the Binding of your script's main scope:

a = 42
p binding.local_variable_defined?(:a) # => true
p TOPLEVEL_BINDING.local_variable_defined?(:a) # => true

def example_method
  p binding.local_variable_defined?(:a) # => false
  p TOPLEVEL_BINDING.local_variable_defined?(:a) # => true


What is a practical use of it?

Besides being a general default binding for your application (which is used in IRB), it can act also as the missing

clean_binding = TOPLEVEL_BINDING.dup

Assuming a more complex/structured application (instead of a single-file script), the top-level binding is mostly empty or consists of just a few important variables.

In fact, this is how it is utilized in stdlib's ERB implementation.

More Idiosyncratic Ruby