Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 134 ยท Metaprogramming

eval and Binding

Learn how Ruby's eval runs strings as code, how Binding captures local variables, why eval is a security risk, and which safer tools to reach for first.

Most Ruby code is written ahead of time and saved in a file. eval flips that around: it takes a string at run time, parses it as Ruby, and runs it. Anything you can type in a script, eval can run from a string that your program built a moment ago. That makes it the most powerful metaprogramming tool in the language, and also the most dangerous one.

This lesson explains how eval works, how a Binding object lets it see local variables, how instance_eval and class_eval accept strings, and why a professional reaches for send, define_method or a lookup table first. Read Closures and Binding and Introduction to Metaprogramming before this lesson, and instance_eval and class_eval for the block forms.

Kernel#eval: running a string

eval(string) compiles the string and runs it in the current context. It returns the value of the last expression, exactly like a method body does. Because the string runs where you called eval, it can read the local variables that are visible at that spot.

Ruby eval runs a string as code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first two calls see x because eval runs inside the same scope. The interesting part is y. The assignment y = 99 works inside the evaluated string, but the variable lives only for that one eval call, so a second eval("y") raises NameError. Your own source code cannot see such variables either. Ruby decides which names are local variables when it parses a file, and the file was parsed before z ever existed, so the bare word z in your code is treated as a method call and the lookup fails. The exception is a Binding object, introduced next: evaluating several strings against the same binding lets them share variables, which is why b.eval("z * 6") prints 42.

eval returns the value of the last expression, so eval("1; 2; 3") returns 3. It is an expression like any other and can be used on the right side of an assignment.

Binding: a saved scope

A Binding object captures a place in your program: the local variables, self, the current method and block. You get one by calling binding. You can pass it to eval as the second argument so the string runs in that captured scope, even if the scope belongs to a method that has already returned. This is the same idea as a closure, packaged as a first-class object.

Ruby Capturing and using a Binding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

make_counter_binding has returned, yet its count is still alive because the binding keeps the scope reachable. local_variable_get and local_variable_set let you read and write variables without building a string, which is always safer than eval. A variable you add with local_variable_set exists only inside that binding, so it shows up in b.local_variables but not in the original method. receiver is the self of the captured scope and source_location is the file and line where binding was called.

Because a binding keeps every local variable in that scope alive, storing bindings carelessly can keep big objects from being garbage collected. Treat them as short-lived tools.

Bindings and templates

The standard library's ERB template engine is the classic user of eval with a binding: the template text is turned into Ruby code, and the binding supplies the variables the template mentions. You will use it in ERB Templates. Test frameworks and debuggers use the same trick, which is how binding.irb can open a console where all your locals are available.

Giving eval a file name and line number

When code inside an eval string fails, the error report needs a place to point to. By default Ruby invents a description such as (eval at main.rb:12). You can pass your own file name and starting line number as the third and fourth arguments, which makes stack traces far easier to read.

Ruby Naming evaluated code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Note that the second argument is the binding. Passing nil means "use the caller's binding". The backtrace lines now read pricing_rule.rb:12 and snippet.rb:7, so a person debugging a rules file knows exactly which snippet failed. Always supply these two arguments when the string comes from a file or a database row.

instance_eval and class_eval with strings

instance_eval and class_eval normally take a block. They also accept a string, and the same file-and-line arguments apply. The difference between the two is the value of self and where def puts new methods.

Ruby Evaluating strings inside an object or a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

instance_eval on one object sets self to that object, so @balance is its instance variable, and a def inside creates a singleton method on only that object (the second Account.new does not respond to audit). class_eval sets self to the class and def adds a normal instance method for every object.

The last loop is the pattern you will see in older libraries: build method source with string interpolation and class_eval it. Notice the \#{amount} in the heredoc. The first #{name} is interpolated while building the string; the escaped one survives as literal text and is interpolated later, when the generated method runs. Mixing the two levels is error-prone, and today define_method does the same job with a block and no string at all.

__FILE__, __LINE__ + 1 is the idiom for class_eval with a heredoc. It points the string's line numbers at the line where the heredoc text begins, so a failure inside the generated code points at your source file.

When evaluated code is broken

An eval string is parsed when the call runs, not when your file loads. A typo you would normally catch the moment the script starts becomes a run-time failure. Syntax mistakes raise SyntaxError, and there is a trap: SyntaxError is a ScriptError, not a StandardError, so a plain rescue => e does not catch it.

Ruby SyntaxError escapes a plain rescue (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The 1 / 0 rule is rescued, but "1 +" is not: the program stops with a SyntaxError that points into (eval at main.rb:2) and shows the offending source line. To handle bad input you must name the class: rescue SyntaxError => e (or rescue ScriptError). Whenever you evaluate text you did not write, handle both StandardError and SyntaxError.

Ruby Handling a SyntaxError explicitly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The security problem

eval does not run "an expression". It runs any Ruby program. If any part of the string comes from a user, a file upload, a URL parameter or a database field a user can edit, the user controls your program. Ruby can read files, delete files, open sockets and run shell commands, so a single eval on untrusted text is a complete remote-code-execution hole.

Here is a harmless demonstration. A "calculator" evaluates what the user types. The user types arithmetic... or something else.

Ruby eval on user input runs anything

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The attacker's text printed output, inspected the file system and returned a value, all through a function that was supposed to add numbers. Replace those calls with File.delete, system("...") or code that sends secrets over the network and you see the real risk.

You cannot make eval safe by filtering the input. Blocklists of "dangerous words" fail because Ruby has many ways to spell the same call (send, string concatenation, const_get, encodings). Older versions of Ruby had $SAFE levels, but that mechanism was removed in Ruby 3.0 because it never provided real isolation. For untrusted code use a separate process with operating-system sandboxing, never eval in your own process.

Safer tools to use first

Almost every real need for eval has a safer replacement. Learn this table; it is also a great interview answer.

You want to... Use this instead
Call a method whose name is in a variable public_send(name, *args)
Find a class from a name Object.const_get("ClassName")
Read or write an instance variable by name instance_variable_get / instance_variable_set
Define many similar methods define_method with a block
Turn text into a number Integer("42"), Float("3.5")
Parse structured data JSON.parse, YAML.safe_load
Choose behavior from user input A Hash of allowed names to lambdas
Use variables from a captured scope Binding#local_variable_get
Ruby Replacing eval with a lookup table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The table lists exactly three operations, so the user can pick only those. Integer("two") raises ArgumentError instead of silently turning bad text into a number, and fetch with a block reports unknown operations with a clear message. public_send is also restricted: system is a private method, so calling it that way fails with NoMethodError. Compare this with send, which ignores visibility, so avoid passing user-controlled names to send.

When eval is reasonable

Experts still use eval, but only when the code is trusted and nothing simpler works:

  • Loading your own configuration or DSL files. instance_eval(File.read(path), path) is how many tools read a Rakefile or similar script. The file is code you wrote or reviewed, and it is not user input. See Building DSLs.
  • Template engines such as ERB, which compile a template to Ruby and evaluate it against a binding.
  • Interactive tools like irb and debuggers, where the person at the keyboard is the user and already has full access.
  • Generated code for hot paths, a performance trick that is rare today. Measure first.

Even then, give every evaluated string a file name and line number, keep it out of reach of untrusted input and prefer the block form of instance_eval or class_eval when you can.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After eval("y = 99") runs at the top level, what happens when your own code later contains the bare word y?

    Ruby decides which names are local variables when it parses the file. A variable created inside eval does not exist in the surrounding code, so the plain word y is treated as a method call and fails with NameError.
  2. 2. What does a Binding object hold?

    A Binding captures the scope where binding was called, including local variables and self, and keeps it alive so eval can use it later.
  3. 3. Why does rescue => e not catch an eval string with a syntax error?

    A bare rescue catches StandardError and its subclasses. SyntaxError inherits from ScriptError, so you must rescue SyntaxError or ScriptError by name.
  4. 4. Which approach is the safest way to let users pick an operation by name?

    A lookup table only runs code you wrote. eval and send execute whatever the user manages to name, and filtering words is easy to bypass.
  5. 5. What is the purpose of passing __FILE__, __LINE__ + 1 to class_eval with a heredoc?

    The file and line arguments label the evaluated code, so an error inside generated methods points at a real place instead of an anonymous eval.

Summary

  • eval(string) parses and runs Ruby code from a string in the current scope and returns the last value; local variables created inside it do not leak out.
  • A Binding captures local variables and self; pass it as the second argument of eval, or use local_variable_get and local_variable_set instead of strings.
  • Give evaluated code a file name and line number so backtraces are readable; use __FILE__, __LINE__ + 1 with heredocs.
  • instance_eval with a string defines singleton methods on one object; class_eval defines instance methods on a class. A block with define_method is almost always better.
  • SyntaxError is not a StandardError, so rescue => e does not catch it.
  • eval on untrusted text is remote code execution and cannot be made safe by filtering; use public_send, const_get, Integer(), parsers and lookup tables.
  • Keep eval for trusted DSL files, templates and interactive tools.

Next: Ractors