Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Binding#eval
static VALUE
bind_eval(int argc, VALUE *argv, VALUE bindval)
{
VALUE args[4];
rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
args[1] = bindval;
return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
}
Evaluates the Ruby expression(s) in string in the context of self. Returns the result of the last expression:
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:
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:
b.eval("puts __LINE__") # => 1 b.eval("puts __LINE__", "foobar.rb", 10) # => 10
Ruby version changes
-
3.0
-
Binding#evalwhen called with one argument will use “(eval)” for__FILE__and 1 for__LINE__in the evaluated code. [Bug #4352] [Bug #17419]
-