From: Dave Thomas Date: 2008-09-01T11:29:26+09:00 Subject: Re: instance_eval/class_eval including/extending modules On Aug 31, 2008, at 9:15 PM, Patrick Li wrote: > 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 > > 2) Klass.instance_eval {def myMethod; end} > > -self is equal to Klass > -so myMethod() is callable by Klass.new <-- this isn't true > > What's wrong with my understanding? I think I'm not understanding def > correctly. Ruby has two separate concepts: self, the current object, and 'the current class', which isn't represented by an externally visible variable. Methods are stored in the later, independent of the value of self. It _is_ confusing, but you can always remember that class_eval creates instance methods and instance_eval creates class methods. There are actually good reasons why this is so. If you want to get deeper into this, I could recommend a certain set of screencasts... Dave