Skip to content
instance method

Module#class_eval

(::String arg0, ?::String filename, ?::Integer lineno) -> untyped
[U] () { (self m) [self: self] -> U } -> U
mod.class_eval(string [, filename [, lineno]]) → obj
mod.class_eval {|mod| block } → obj

Alias of #module_eval

Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.

Example
class Thing
end
a = %q{def hello() "Hello there!" end}
Thing.module_eval(a)
puts Thing.new.hello()
Thing.module_eval("invalid code", "dummy", 123)

produces:

Hello there!
dummy:123:in `module_eval': undefined local variable
    or method `code' for Thing:Class
See also #module_eval #autoload? #class_exec #autoload also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0