Skip to content

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

instance method

Binding#eval

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

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

Example
def get_binding(param) = binding
b = get_binding("hello")
b.eval("param")   #=> "hello"

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
b.eval("puts __FILE__") # => "(eval at test.rb:4)"
b.eval("puts __FILE__", "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
b.eval("puts __LINE__") # => 1
b.eval("puts __LINE__", "foobar.rb", 10) # => 10

Ruby version changes

  1. 3.0