Plough => Ruby

Journey through ruby

Define_method, Instance_eval and Class_eval

Right, so this is a tad confusing and the reason I am explaining is to ensure that I understand it properly.

instance_eval - It creates singleton methods on the object it is invoked on. If it is invoked on a Class object then these methods become singleton methods of the class. Some people would call them “class methods” but these are simply methods in an object’s singleton class. Here’s the code:

SomeObject.instance_eval (def singleton_method; "singleton_method";end)

class_eval - It creates an instance method on the object. Simple there is nothing confusing about this. Here’s an example:

SomeObject.class_eval(def instance_method;"instance_method";end)

Now, define method when used inside either class_eval or instance_eval s immune to the usual behaviour.

Why, you may ask?

Because the documentation says so. As per the documentation “define method - Defines an instance method in the receiver”. Therefore, it does not matter if you use define_method inside class_eval or instance_eval it would always create an instance method. Now, the question to ask is - “Is there no way to define a singleton method using defne_method?”. Well, I still need to investigate that. It would probably be in an update to this post. Hope it all makes sense. Ruby metaprogramming is awesome only if you know what you are doing and to get to that stage one needs to spend countless hours metaprogramming.