From: "David A. Black" Date: 2008-06-15T03:40:51+09:00 Subject: Re: Knowing which subclass called a superclass class method Hi -- On Sun, 15 Jun 2008, Rob Boellaard wrote: > to continue on the same theme, if this is the class: > > > class S > > puts "1" + self > > def self.doSomething > puts "2" + self Do you mean self.name, in both cases? > end > > end > > > I get: > > 1 S > 2 A I assume that you've done: class A < S end A.doSomething # or do_something, using Ruby style naming and that you didn't really get magically-inserted spaces :-) > why is there this difference? and is there a way to get A in the first > case? The code inside a class definition gets executed when the class definition is read in. Code at the top level of the definition, like your puts statement, gets executed right away. Method definitions get executed in the sense that the methods get defined, but the methods themselves don't get executed until they're called. So your definition of S does two things: * prints out "1" + self.name * defines a method, to be called later If you want to do the puts'ing for a subclass, you could do: class S def self.inherited(c) c.class_eval { puts "1" + self.name } end end (or just puts "1" + c.name) David -- Rails training from David A. Black and Ruby Power and Light: ADVANCING WITH RAILS June 16-19 Berlin ADVANCING WITH RAILS July 21-24 Edison, NJ See http://www.rubypal.com for details and updates!