0.3 Class Eval

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.

Example Code:

Output Window

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.

Output Window

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.

Summing it all up

Doing any evals with Ruby is fairly expensive (in performance) as it needs to parse strings if required, and then do a tree walk to execute it. And we've already seen that evals can lead to really ugly and evil scenarios. Therefore, it is important to be careful when using these eval methods. They are best avoided for most use-cases.

Congratulations, guest!

% of the book completed


This lesson is Copyright © 2011-2024 by Sidu Ponnappa and Jasim A Basheer