Skip to content

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

instance method

Module#module_eval

(::string code, ?::string? filename, ?::int lineno) -> untyped
[U] () { (self mod) [self: self] -> U } -> U
module_eval(string, filename = nil, lineno = 1) → obj
module_eval { |mod| ... } → obj

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:

Example
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:

Example
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:

Example
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:

Example
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:

Example
class Foo
  GREETING = "hello"
end

Foo.module_eval("puts GREETING") # => "hello"

Foo.module_eval { puts GREETING } # => NameError: uninitialized constant GREETING