On Feb 8, 2007, at 4:33 PM, dblack / wobblini.net wrote:
>> class C; end
>> class D < C; end
>> class E < C; end
>> class D; @@beta = 42; end      # establishes @@beta for B and  
>> descendants
>> class C; @@beta = 52; end      # establishes @@beta for A and  
>> descendents
>>                              # *excluding* B since that branch  
>> already
>>                              # has @@beta defined!
>
> I think there's an error here; C and D aren't related to A and B.

My bad, pay attention to the code, not the comments.  Comments should
have had D for B and C for A.

>
>> def A.show_alpha
>> @@alpha                        # lexically at top-level!!!
>> end
>> p A.show_alpha                   #52!
>
> I'm not sure whether it's lexical scoping or just the fact that A's
> singleton class is sharing @@alpha with Object.  If you do:
>
>   class String
>     p @@alpha
>   end
> you'll also get 52.

@@alpha has already been established in Object, which
takes precedence over anything in String (since it was
defined first).  Consider:

irb(main):001:0> class A; end
=> nil
irb(main):002:0> class B
irb(main):003:1>   def A.foo
irb(main):004:2>     @@alpha
irb(main):005:2>   end
irb(main):006:1>   @@alpha = 'B scope'
irb(main):007:1> end
=> "B scope"
irb(main):008:0> A.foo
=> "B scope"

In this example the definition of A::foo is lexically within the
(class B;end) block and so @@alpha is resolved relative to B. Not to
the top-level or relative to B's singleton class.

> Also, if you do:
>
>   class << A
>     @@alpha = 1
>   end
>
>   p @@alpha
>
> Object's @@alpha will be 1.

Well it turns out that the scope created by "class <<A; end" is not
at all like the scope created by "class A; end", at least with respect
to class variables.  Throw away all the stuff above and consider fresh:

class A
   @@alpha = 1
end

p (class <<A; @@alpha; end)    # warning, top-level scope for @@alpha


In fact, I couldn't figure out how to even create a class variable
that was anchored to the singleton class of a class.  I didn't try too
hard though...

Gary Wright