Class: Binding

Inherits:
Object
  • Object
show all
Defined in:
lib/extensions/binding.rb

Overview

Ruby’s built-in Binding class doesn’t contain any methods. It is merely a “context” object that can be used in calls to Kernel.eval, like this:

def example(_binding)
  return eval("x", _binding)
end

x = 55
current_binding = Kernel.binding
example(current_binding)                # -> 55

The most useful method introduced to Binding by the extensions package is Binding.of_caller. It allows you to access the binding of the calling method, thus enabling you to access local variables in that scope. The other methods are a convenient object-oriented facade for operations that you can already do with #eval as demonstrated above. Here is an example that showcases all of the Binding methods included in extensions.

def example
  Binding.of_caller do |b|
    puts "x + y = #{b.eval('x + y')}"
    puts "x = #{b[:x]}"
    puts "Local variables: " + b.local_variables.join(', ')
    b[:y] += 1
    puts "Changed value of y in calling context to #{b[:y]}"
    puts "Is 'z' defined in calling context?  " + (b.defined?(:z) ? 'Yes' : 'No')
  end
end

x = 5
y = 17
example
y              # -> 18

Binding.of_caller was written by Florian Gross. The other methods were written by Tom Sawyer.