From: Justin Collins Date: 2006-07-26T06:00:54+09:00 Subject: Re: "Self" confusion --------------050509070805030407070207 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8bit Sch�le Daniel wrote: >>> class Yoghurt >>> def self.a >>> "yoghurt self" >>> end >>> def Yoghurt.a >>> "yoghurt" >>> end >>> >>> p Yoghurt.a >>> p self.a >>> end > > I am not Ruby expert, but isn't Yogurt.a and self.a the same thing? > Then the last one simply overwrites the preceding one. > > From this I think that > Object.a and self.a should act similary, don't they? > > > > -- > Daniel > Yes it is exactly the same _if_ you are inside the definition of the class. That is why I was trying to say that the top level of Ruby cannot be inside the definition of Object, because then p self.a would be the same as p Object.a but it isn't, because we are not in a class definition. However, def self.a "Hi from self" end is the same as def a "Hi from self again" end and the latter will overwrite the first, as we are defining methods for this instance of the class. From Pickaxe 1: " At the top level, we're executing code in the context of some predefined object. When we define methods, we're actually creating (private) singleton methods for this object. Instance variables belong to this object. And because we're in the context of |Object|, we can use all of |Object|'s methods (including those mixed-in from |Kernel|) in function form. This explains why we can call |Kernel| methods such as |puts| at the top level (and indeed throughout Ruby): these methods are part of every object." -Justin --------------050509070805030407070207--