A blog on programming, artificial intelligence,.. an my works in it

Wednesday, January 21, 2009

Class Eval & Instance Eval at Class level

The ruby language is an interpreted language ( damn I'm starting with quite a stupid phrase) as such upon writing the code there is really nothing defined until read by the interpreter.

In order to do so the ruby interpreter defines objects of type "Class" to read,defineand contain the class specification you have written in your .rb

instance_eval: Evaluates the string or block within the context of the recieving object. Object being the key word of the phrase.
class_eval: Evaluates the string or block within the context of the module/class.

When browsing the internet you might find the following sentence: instance_eval adds class methods and class_eval adds instance methods.... the wording here is a bit of bullsh*** the library specifies that instance_eval is evaluated in the context of the recieving object. What gives?

Lets use the following example:
Class Test
Test.instance_eval do
def testmodulemethod(x)
x << " Y"
return x
puts Test.testmodulemethod("Vicente")
puts Test.superclass
Vicente Y
Before reading the following paragraph bear in mind that I am using the "Class" to represent the object/mechanism/whatever implemented in ruby to contain specifications of what in programming theory we now as a class.

You have been warned, read ahead :-)

As you can see what we really did was add a method to the object named Test which is of the class "Class" that is the internal that contains the definition of a class. instance_eval on the Test "Class" object does not add class methods in the sense that it does not add a method to the class defined in the object infact what it does is add an instance method to the Test object.

Some other methods of the Test object are method_added, method_defined? ... so you can forsee the internals: Test gets converted into an object in the interpreter that contains our definition of the class Test defined in our script and by performing instance_eval we add methods to this object instance of "Class".
When we do a class_eval on a Class object we are adding a method to the definition held with in.

As a summary:
-instance_eval adds instance methods( methods available only on that object instance) on the "Class" object, the object that represents our class internally. This is totally different from adding class methods.

-class_eval adds methods to the class represented/defined inside the "Class" object.