Dominik Bathon
2/20/2006 4:10:00 PM
On Mon, 20 Feb 2006 15:22:04 +0100, Tony Mobily <merc@mobily.com> wrote:
> Hello,
>
> Thanks to the code in attach, I've figured out what is now completely
> obvious to me:
>
> CLASS VARIABLE (@@something)
> - Inherited by subclasses
> - SAME ALLOCATION: If it's changed in Child, then it will change in
> Parent
>
> CONSTANTS (Something)
> - Inherited by subclasses
> - PRIVATE ALLOCATION: If it's changed in Child, it will NOT change in
> parent
>
> CLASS INSTANCE VARIABLES (@something)
> - NOT Inherited by subclasses. They will simply be nil. Scope = Class
> - DIFFERENT ALLOCATION: If it's changed in Child, it will NOT change in
> parent
But there is more fun when singleton classes get involved:
class A
@@var = :A
C = :CA
end
class B
@@var = :B
C = :CB
a = A.new
class ::A
p [@@var, C] # => [:A, :CA]
def foo
[@@var, C]
end
end
def a.bar
[@@var, C]
end
class << a
p [@@var, C] # => [:B, :CB]
def baz
[@@var, C]
end
end
p a.foo # => [:A, :CA]
p a.bar # => [:B, :CB]
p a.baz # => [:B, :CB]
p [@@var, ::A::C, C, class << a;C;end] # => [:B, :CA, :CB, :CB]
class << a
@@var = :ASing # this changes B's @@var [*]
C = :CASing # this creates a new C for a's sing. class
end
p [@@var, ::A::C, C, class << a;C;end] # => [:ASing, :CA, :CB, :CASing]
p a.foo # => [:A, :CA]
p a.bar # => [:ASing, :CB]
p a.baz # => [:ASing, :CASing]
end
Some points:
- singleton classes don't have their own class variables, but they can
have their own constants
- constant and class var lookup use the lexical scope, so it depends
"where" you do something (that's why bar's C and baz's C are different)
- (lexical) singleton-class-scopes are skipped when accessing class vars
(that's why [*] changes B's @@var and not A's @@var)
I hope that helps and doesn't totally confuse you ;-)
Dominik