Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Module#module_eval
static VALUE
rb_mod_module_eval_internal(int argc, const VALUE *argv, VALUE mod)
{
return specific_eval(argc, argv, mod, FALSE, RB_PASS_CALLED_KEYWORDS);
}
Evaluates the string or block in the context of self. Returns the result of the last expression.
When string is given, evaluates the given string in the context of self:
class Foo; end Foo.module_eval("def greeting = puts 'hello'") Foo.new.greeting # => "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:
class Foo; end Foo.module_eval("puts __FILE__") # => "(eval at ../test.rb:3)" Foo.module_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:
class Foo; end Foo.module_eval("puts __LINE__") # => 1 Foo.module_eval("puts __LINE__", nil, 10) # => 10
When a block is given, evaluates the block in the context of self:
class Foo; end Foo.module_eval do def greeting = puts "hello" end Foo.new.greeting
However, constant and class variable lookup differs between string and block. When string is given, constant and class variables are looked up in the context of self. When a block is given, the context of the lookup is not changed:
class Foo GREETING = "hello" end Foo.module_eval("puts GREETING") # => "hello" Foo.module_eval { puts GREETING } # => NameError: uninitialized constant GREETING