From: Rick DeNatale Date: 2006-10-27T11:13:35+09:00 Subject: Re: why is my singleton method called before the class is initialize? On 10/26/06, matt neuburg wrote: > bachase@gmail.com wrote: > > > Consider: > > > > class BigGuy > > def initialize > > @favorites = ["a","b","c"] > > end > > > > class << self > > def display_favs > > class_eval "p @favorites" > > end > > end > > end > > > > class LittleGuy < BigGuy > > display_favs > > end > > > > Why does this display "nil"? I expected the initialize of BigGuy to > > occur prior to invoking display_favs. Any other construction I should > > be using to get my desire behavior of the constructor of the base class > > getting called prior to singleton methods called from the child class? > > "Initialize" is called when the class is instantiated (i.e. with new). > You are never instantiating this class, so "initialize" is never called. True, but kind of beside the point. The initialize method if and when it is called will set the instance variable @favorites in a new INSTANCE of BigGuy. class BigGuy ... class << self def display_favs class_eval "p @favorites" end end end This makes display_favs a class method of BigGuy. In the method display_favs self is the class object BigGuy. so class_eval "p @favorites" is the same as BigGuy.class_eval "p @favorites" which is printing a class instance variable of BigGuy which doesn't exist. And... class LittleGuy < BigGuy display_favs end inside this class definition, self is LittleGuy so display_favs is equivalent to: LittleGuy.display_favs which executes BigGuy::display_favs by inheritance which prints the uninitialized class instance variable @favorites. Note also that the class instance variable @favorite in BigGuy is different from the clas instance variable @favorite in LittleGuy, although neither one is initialized. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/