From: Rick DeNatale Date: 2007-11-16T06:28:05+09:00 Subject: Re: instance variables as class variable ? On Nov 15, 2007 3:15 PM, wbsurfver@yahoo.com wrote: > > I'm trying to get a handle on why the following code works by printing > out 'frog' > because @x looks like instance variable syntax. I know that some of > these things don't work the way I'd expect. > > class Test > @x = 'frog' > > class << self > attr_reader :x > end > > end > > puts Test.x Well it is an instance variable, of the class. This is commonly called a class instance variable, not to be confused with a class variable. Within the lexical scope of class..end self is the class, so @x is an instance variable of the class. Consider this: class Test # self here is Test which holds the methods for its instances attr_reader :x # this is actually a message sent to Test, which defines an instance method end Now when you say class Test class << self # (which could also be class << Test) #self becomes the singleton class of Test. attr_reader :x # and here the attr_reader message is sent to Test's singleton class # resulting in an "instance method" in the singleton class which is a # class method of Test end end -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/