1. Computing

Eval: Running Code on the Fly


Most non-compiled languages have some kind of eval function, which will take a string and execute it as code. The eval method in Ruby accomplishes this, and is rather straightforward.

As usual, let's jump right in with a code example. This example will run the code in the string and print its result to the screen.

#!/usr/bin/env ruby

code = "Time.now"
result = eval(code)
puts result

The method call Time.now is stored in a string. It's not executed, compiled or even looked at (other than determining that it's a string literal) by the Ruby interpreter. It's just a string, anything could be in there. However, once you call the eval method, that all changes. The Ruby interpreter parses this string as if it were Ruby code and runs it. It will return whatever the code evaluates to.

Simple enough, but why would anyone want to use this? There's a lot of debate whether eval should be used, and it's often considered bad form and hackish. There are also some pretty big security implications in using eval at all in your code, so it's not something that should be used lightly. There is one great use for eval though: developer consoles. Adding a way for programmers to issue Ruby commands to your program directly by using eval can be a powerful debugging tool and quite easy to implement.

But there's one more feature to explore related to eval: bindings.

  1. About.com
  2. Computing
  3. Ruby
  4. Advanced Ruby
  5. Eval: Running Code on the Fly

©2014 About.com. All rights reserved.