1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

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.

Explore Ruby
By Category
    rubyRubycomputeTechbc50405f6500016666800be03c53ced14a0007b41c0042dbhttp://ruby.about.comod526F6F7444924liveMichael MorinrubyguideLmC0001qzNIP11970-01-0110/od/index.htm0526F6F741approved/od
  1. About.com
  2. Tech
  3. Ruby
  4. Advanced Ruby
  5. Eval: Running Code on the Fly

©2015 About.com. All rights reserved.