Obviously there’s some confusion though Matz.
In most languages (C++, Java, Delphi, etc.), class variables (static’s)
are scoped by the class, not the entire inheritance chain.
It’s just… different. Once people understand it, it’s fine, bug I
definitely don’t think it’s obvious.
···
-----Original Message-----
From: Yukihiro Matsumoto [mailto:matz@ruby-lang.org]
Sent: Thursday, August 21, 2003 10:50 AM
To: ruby-talk ML
Subject: Re: Class variables - a surprising result
Hi,
In message “Re: Class variables - a surprising result” on 03/08/21, David Heinemeier Hansson david@loudthinking.com writes:
Class variable allocation is per class scope, not per subclass scope.
Sub1, Sub2 and Sup really do share their class variables. Now don’t
ask me for the “why exactly”…I was fooled by this as well. I don’t know why I intuitively would
think that a subclass would get its own scope, but I did. Having your
own scope as a subclass would be a really neat addition, though. But
perhaps a reason from Matz would shed light?
They are variables. If you can’t update values, how they can be
variables.
class Sup
@@x = "A" # declare @@x, set @@x as "A"
def test
print @@x
end
end
class Sub1 < Sup
@@x = "B" # set @@x as "B"
end
class Sub2 < Sup
@@x = "C" # set @@x as "C"
end
Sup.new.test # print the value of @@x ("C")
Sub1.new.test # ditto.
Sub2.new.test # ditto.
Class variables are like global variables whose scope is limited to the
inheritance tree.
matz.