Skip to Main Content
Professional Ruby on Rails™
book

Professional Ruby on Rails™

by Noel Rappin
February 2008
Intermediate to advanced content levelIntermediate to advanced
479 pages
14h
English
Wrox
Content preview from Professional Ruby on Rails™

14.1. Eval and Bindings

Many scripting languages have a facility to allow an arbitrary string to be executed at runtime. In Ruby, that feature comes from the eval method. Here's an example of that method:

>> eval("2 + 2")
=> 4

By default, variables in the code string are evaluated in the current context, as follows:

>> x = 3
=> 3
>> y = 5
=> 5
>> eval("x * y")
=> 15

However, you can evaluate the string in a more-or-less arbitrary environment by passing in an optional second argument, which must be a Ruby binding. Bindings are kind of odd entities that encapsulate the context of a block, which is basically a lookup table that stores the values of all accessible variables and constants. From the binding, the state of variable values when the block is created can be revisited.

Every block or Proc object defines its own binding, within which it can set local variable values. Under normal circumstances, this binding is accessed only when the block is executed, to determine the values of variables used by the block. However, you can retrieve just the binding and execute an arbitrary statement within it using the variable values as defined when the block was created.

Here's a test script that shows how bindings work:

def some_crazy_thing
  a = 10
  b = 20
  Proc.new {c = 10}
end

p eval("a * b", some_crazy_thing.binding)

The method some_crazy_thing sets a couple of variables and returns a Proc object. The last line of the script takes that block, grabs its binding, and tries to add two variables. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher
Rails 4 in Action

Rails 4 in Action

Yehuda Katz, Rebecca Skinner, Stephen Klabnik, Ryan Bigg

Publisher Resources

ISBN: 9780470223888Purchase book