From: "Peña, Botp" Date: 2008-09-01T11:48:24+09:00 Subject: Re: instance_eval/class_eval including/extending modules From: Patrick Li [mailto:patrickli_2001@hotmail.com] # I must say that I also find the difference between # instance_eval/class_eval and include/extend extremely confusing. # If someone clearly knows the fundamental rules, please please share. # Here's my understanding: # def myMethod; end # -creates a method "myMethod" callable by instances of self. # Here's a list of situations that I'm having trouble with: # 1) class Klass # def myMethod; end # end # -self is equal to Klass # -so myMethod() is callable by Klass.new generally, callable by instances of Klass # 2) Klass.instance_eval {def myMethod; end} # -self is equal to Klass # -so myMethod() is callable by Klass.new no. the instance here is Klass, not those created/instanciated w Klass.new. So you are creating a class method for Klass. Remember, classes are objects too, ergo there are class methods too. # What's wrong with my understanding? I think I'm not understanding def # correctly. observe eg, class Klass def mymethod; end end #=> nil k=Klass.new #=> # k.mymethod #=> nil ok. fine. let's try the other way, ie instance_eval. k.instance_eval{def mymethod3; end} #=> nil k.mymethod3 #=> nil fine still. now let us try it for Klass itself. Klass.mymethod NoMethodError: undefined method `mymethod' for Klass:Class oops ;) maybe, we can do it w mymethod3 Klass.mymethod3 NoMethodError: undefined method `mymethod3' for Klass:Class oops still ;) Ok. let us define a method that works only for Klass. Klass.instance_eval{def mymethod2; end} #=> nil k.mymethod2 NoMethodError: undefined method `mymethod2' for # heheh, it does not work for instances/creations of Klass. now, let us test it for Klass itself. Klass.mymethod2 #=> nil ah, we see. hth. kind regards -botp