Cover by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Evaluating Strings and Blocks

One of the most powerful and straightforward reflective features of Ruby is its eval method. If your Ruby program can generate a string of valid Ruby code, the Kernel.eval method can evaluate that code:

x = 1
eval "x + 1"  # => 2

eval is a very powerful function, but unless you are actually writing a shell program (like irb) that executes lines of Ruby code entered by a user you are unlikely to really need it. (And in a networked context, it is almost never safe to call eval on text received from a user, as it could contain malicious code.) Inexperienced programmers sometimes end up using eval as a crutch. If you find yourself using it in your code, see if there isn’t a way to avoid it. Having said that, there are some more useful ways to use eval and eval-like methods.

Bindings and eval

A Binding object represents the state of Ruby’s variable bindings at some moment. The Kernel.binding object returns the bindings in effect at the location of the call. You may pass a Binding object as the second argument to eval, and the string you specify will be evaluated in the context of those bindings. If, for example, we define an instance method that returns a Binding object that represents the variable bindings inside an object, then we can use those bindings to query and set the instance variables of that object. We might accomplish this as follows:

class Object # Open Object to add a new method def bindings # Note plural on this method binding # This is the predefined ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required