Bindings

The eval method may take an optional “binding” argument that, if provided, causes the evaluation to be done within a specific scope or “context.” It probably won’t come as any surprise to discover that, in Ruby, a binding is an object that is an instance of the Binding class. You can return a binding using the binding method. The documentation of eval in the Ruby class library provides this example:

binding.rb

def getBinding(str)
    return binding()
end
str = "hello"
puts( eval( "str + ' Fred'" ) )                    #=> "hello Fred"
puts( eval( "str + ' Fred'", getBinding("bye") ) ) #=> "bye Fred"

Simple as it may look, this example may take a bit of thinking about in order to understand what’s going on. Essentially, the first call to puts evaluates str in the ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.