From: "David A. Black" Date: 2008-09-02T18:14:26+09:00 Subject: Re: Self and Current Class Hi -- On Tue, 2 Sep 2008, Pedro Silva wrote: > Thomas, thanks for your reply. >> >> So I guess the general rule is: inside module declaration, both self and >> current class are set to the module we're declaring. Outside module >> declarations, current class is set to the eigenclass of self. >> >> I hope this is not a complete mess and rubbish :) > > Consider this case: > > class SomeClass > # self is SomeClass, current class is SomeClass > puts "Class Level - #{self}" > > def some_method > # self is an instance, current class is SomeClass > puts "Some Method - #{self}" > > def self.some_inside_class_method > # self is an instance, current class is instance's singleton > class > puts "Inside class method - #{self}" That's not a class method. self is an instance of SomeClass; you're defining a singleton method on that instance. Every time you do: def obj.something you're defining a singleton method "something" on obj. self is just an alias for a particular object at a particular point in runtime. > end > > def some_inside_instance_method > # self is an instance, current class is SomeClass > puts "Inside instance method - #{self}" > end I'm not sure what you mean by "inside" in the method name. It's just an instance method. > # self is an instance, current class is instance's singleton class > instance_eval { puts "Instance instance_eval - #{self}" } > # no class_eval for instances > end > > def self.class_method > # self is SomeClass, current class is SomeClass's singleton class > puts "Class method - #{self}" > end > > # self is SomeClass, current class is SomeClass's singleton class > instance_eval { puts "Class instance_eval - #{self}" } > > # self is SomeClass, current class is SomeClass > class_eval { puts "Class class_eval - #{self}" } > end > > Are all the comments correct about self and current class value and are > all cases covered (current class modification)? > Is def the only method that uses the current class value? It's a keyword, rather than a method, but I think it is the only thing that cares about the notion of "current class", at least as I understand that notion. (I admit it's not one that I've paid much attention to, by that name, though of course I like to know what 'def' will do at any given time.) David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!