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

