Binding
Binding.new, binding() Returns:
Binding · Updated March 13, 2026 · Core Classes scope context evaluation variables
The Binding object represents the current scope in Ruby. It encapsulates local variables, constants, method visibility, and self, allowing you to capture and later evaluate code in that context.
Creating Bindings
# Get current binding
b = binding
# From specific scope
def get_binding
local_var = "hello"
binding
end
b = get_binding
Practical Examples
Eval with Binding
# Evaluate code in a specific context
x = 10
b = binding
eval("x + 5", b) # => 15 (uses x from binding)
Capturing Variables
def create_closure
secret = "hidden"
binding
end
b = create_closure
puts b.local_variables # => [:secret]
# Access variable through binding
value = b.local_variable_get(:secret)
puts value # => "hidden"
Passing Context
def execute_in_context(code, ctx)
eval(code, ctx)
end
name = "Ruby"
ctx = binding
execute_in_context("puts \"Hello, #{name}!\"", ctx)
Method Visibility
class MyClass
private
def secret_method
"hidden"
end
def public_binding
binding
end
end
obj = MyClass.new
b = obj.public_binding
# Can call private method through binding
eval("secret_method", b) # => "hidden"
Template Systems
class Template
def render(template, locals = {})
b = binding
locals.each { |k, v| b.local_variable_set(k, v) }
eval("\"#{template}\"", b)
end
end
t = Template.new
puts t.render("Hello, #{name}!", name: "World")
Debugging
def debug_scope
puts "Local variables: #{binding.local_variables}"
puts "Self: #{binding.receiver}"
puts "File: #{binding.source_location}"
end
Binding Methods
# Get local variable
binding.local_variable_get(:name)
# Set local variable
binding.local_variable_set(:name, "value")
# Check if variable exists
binding.local_variable_defined?(:name)
# Get all local variables
binding.local_variables
Source Location
# Where was this binding created?
location = binding.source_location
# => ["/path/to/file.rb", 10] [file, line]
Use Cases
- Implementing template engines
- Domain-specific languages (DSLs)
- Debugging tools
- Code evaluation in restricted contexts
- Capturing closures with state