On 5/1/07, Logan Capaldo <logancapaldo / gmail.com> wrote:
> On 5/1/07, Ball, Donald A Jr (Library) <donald.ball / nashville.gov> wrote:
> >
> >
> > class A
> >   class << self
> >     @var = 'foo'
> >     attr_accessor :var
> >   end
> > end
> >
> > to no avail. Also tried doing it in an initialize method. I'm still
> > missing something key, I think.
>
>
> class A
>   @var = 'foo'
>   class << self
>      attr_accessor :var
>   end
> end
>
> (warning, the following explanation is not really correct)
> class << self is sort of A's class (the class of the class) (It's actually
> A's singleton class). By putting @var='foo' inside class << self you set the
> class of A's instance var @var to 'foo' not A's @var to foo.

Going a little further in answering Donald's question.

Instance variables come into being when they are initialized by code
running in the context of the instance.  Usually that's method code.

This works in the case of class methods, class instance variables are
just instance variables of the class.

However since, I think what we are looking for is a way to initialize
class instance variables in a way analogous to class variables, we
really don't always want to define a method.  Here's one way to
accomplish class instance variable intialization in-line in a class
(re)definition.

 class A
   instance_eval {@var = 'foo'}
   class << self
     attr_accessor :var
   end
 end

since within the class (re)definition self IS the class, instance_eval
runs the block in the context of the class.

-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/