Eval for classes
class_eval
is much simpler than instance_eval
which works on metaclasses (or the singleton object). It works on the class as if you were opening it in a text editor and adding new state or behaviour to it.
The zen
method is defined on all the instances (note that there are two) of the class Monk
. And @zen
is assigned 42
in the initialize
method. Hence, @zen
and zen
are instance variables and instance methods, respectively. Take note of how our old
instance behaves: because initialize
was defined after he was initialized, he does not get the default value of 42. However, because the zen
method is an instance method on the class, we can call zen
on him as soon as it's been defined by class_eval
. Neat, huh?
class_eval
is a method on Module
. Hence, it is restricted even further to just scoping within a class or a module, making it slightly less versatile than instance_eval
.
Try this simple exercise similar to the last one from instance_eval
. Increment @zen
to satisfy @zen == 42
through a method zen
defined on an instance of Monk
using class_eval
.
There is also a method on Module
called module_eval
which is just an alias to class_eval
. It's a better practice to use this when you know you're dealing with a Module
and not a Class
.