Skip to Content
The Ruby Programming Language
book

The Ruby Programming Language

by David Flanagan, Yukihiro Matsumoto
January 2008
Beginner to intermediate
446 pages
14h 45m
English
O'Reilly Media, Inc.
Content preview from The Ruby Programming Language

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 ...
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

Metaprogramming Ruby 2

Metaprogramming Ruby 2

Paolo Perrotta

Publisher Resources

ISBN: 9780596516178Supplemental ContentErrata Page