The Difference Between instance_eval and class_eval in Ruby
written by Steven on August 01, 2012
The Ruby methods instance_eval and class_eval seem to be really straight forward, until you start using them. Then you realize that the whole world seems ass backwards. Let's look at an example:
The first conclusion to be drawn from this is that instance_eval is for classes and class_eval is for instances, which creates a "WTF?!" moment. But don't worry, this isn't quite the right way of looking at it. Let's see what happens when we call the eval methods on an instance of a object:
So what have we discovered? We can use instance_eval on any object, even class objects (remember in Ruby everything is an object, even classes are objects). Because it's eval-ing on the receiver, if it's used on an instance of an object then obviously it evals on that instance creating an instance method. And if it's used on a class object then, again obviously, it evals on the class creating a class method. (I say obviously a bit tongue in cheek here.)
On the other hand class_eval can only be called on classes or modules and it evals on the instances of the class/module creating instance methods.
on and instance of an object | on a class |
|
|---|---|---|
|
instance_eval | Acts on the receiver (self), the instance. "string2".instance_eval { p self} | Acts on the receiver (self), the class. p String.from_instance_eval |
|
class_eval | Not available. | Acts on any instance of the class. "string".from_class_eval |
P.S. module_eval is exactly the same as class_eval. Either can be used for modules or classes.
Leave a Comment

Steven Bristol has written code for the past 20 years. He like green vegetables and kittens, oh and butterflies too. He loves to throw ninja stars at his enemies.
