Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Kernel#eval

(::string src, ?::Binding? scope, ?::string filename, ?::int lineno) -> untyped
eval(string, binding = nil, filename = default_filename, lineno = 1) → obj

Evaluates the Ruby expression(s) in string. Returns the result of the last expression.

Example
str = "Hello"
eval("str + ' World'") # => "Hello World"

If binding is given, which must be a Binding object, the evaluation is performed in its context. Otherwise, the evaluation is performed in the context of the caller.

Example
def get_binding(str) = binding
str = "Hello"
eval("str + ' World'", get_binding("Bye")) # => "Bye World"

If the optional filename is given, it will be used as the filename of the evaluation (for __FILE__ and errors). Otherwise, it will default to (eval at __FILE__:__LINE__) where __FILE__ and __LINE__ are the filename and line number of the caller, respectively.

Example
eval("puts __FILE__") # => "(eval at test.rb:1)"
eval("puts __FILE__", nil, "foobar.rb") # => "foobar.rb"

If the optional lineno is given, it will be used as the line number of the evaluation (for __LINE__ and errors). Otherwise, it will default to 1.

Example
eval("puts __LINE__") # => 1
eval("puts __LINE__", nil, "foobar.rb", 10) # => 10

Ruby version changes

  1. 3.0
    • Kernel#eval when called with two arguments will use “(eval)” for __FILE__ and 1 for __LINE__ in the evaluated code. [Bug #4352]

See also #__dir__ #exec #Complex #exit also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0