Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Kernel#eval
VALUE
rb_f_eval(int argc, const VALUE *argv, VALUE self)
{
VALUE src, scope, vfile, vline;
VALUE file = Qundef;
int line = 1;
rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline);
StringValue(src);
if (argc >= 3) {
StringValue(vfile);
}
if (argc >= 4) {
line = NUM2INT(vline);
}
if (!NIL_P(vfile))
file = vfile;
if (NIL_P(scope))
return eval_string_with_cref(self, src, NULL, file, line);
else
return eval_string_with_scope(scope, src, file, line);
}
Evaluates the Ruby expression(s) in string. Returns the result of the last expression.
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.
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.
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.
eval("puts __LINE__") # => 1 eval("puts __LINE__", nil, "foobar.rb", 10) # => 10
Ruby version changes
-
3.0
-
Kernel#evalwhen called with two arguments will use “(eval)” for__FILE__and 1 for__LINE__in the evaluated code. [Bug #4352]
-