liveBook · Manning

Eval

As explained in The Well-Grounded Rubyist, Fourth Edition

eval is a Ruby method that parses and executes Ruby code supplied as a string within a specified execution context.

Ruby’s eval parses and executes a string as Ruby code at runtime. It is the most direct—and most dangerous—member of the eval family, because it performs string evaluation without adding a gentler context-specific behavior. section 14.4 section 14.4.1

Evaluating an expression and creating a method

eval("2+2") returns 4. A dynamically assembled string can also define and call a method: eval("def #{m}; puts 'Hi!'; end") creates the method named by m, and eval(m) invokes it. section 14.4.1

A second argument can provide a Binding object, which captures local variable bindings at a point in execution. eval then resolves local variables through that binding, allowing code such as puts str to access a variable outside the calling method’s ordinary scope. section 14.4.1

Treat dynamically evaluated strings as a security boundary:

  • Avoid evaluating uncertain strings, especially user input from forms or files; injected code could perform destructive system operations. section 14.4.2
  • Recognize that strings written entirely by the programmer are generally no less secure than that programmer’s program file, while dynamically generated uncertain strings greatly increase risk. section 14.4.2
  • Compare eval with instance_eval and class_eval, which can evaluate strings but also shift self or enter a class-definition context, and may accept blocks. section 14.4
>> eval("2+2")
=> 4

A minimal irb-sized expression makes eval’s basic behavior immediately visible. section 14.4.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains direct execution, Binding-based scope resolution, related eval methods, and security hazards without detailing parser or VM internals.
Examples
Demonstrates arithmetic evaluation, dynamically named methods, and access to a top-level local variable through binding.
What it assumes
Assumes Ruby methods and local variables, while defining Binding and showing from examples how execution context affects variable lookup.
What you can do after
Evaluate/understand how Ruby executes code strings, supplies bindings, and exposes dangerous injection paths.
How it connects
Connects eval with Binding, instance_eval, class_eval, module_eval, and runtime method definition.

Also explained in

Compare how 2 books explain eval →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.