From: dblack@... Date: 2003-08-21T21:56:59+09:00 Subject: Re: Class variables - a surprising result Hi -- On Thu, 21 Aug 2003, [iso-8859-1] Ged Byrne wrote: > class Sup > @@x = "A" > def test > print @@x > end > end > > class Sub1 < Sup > @@x = "B" > end > > class Sub2 < Sup > @@x = "C" > end > > Sup.new.test > Sub1.new.test > Sub2.new.test > >>> CCC > > I think I know whats going on. > > When a variable is first used, that is where it is > declared. Unlike Java there is no separate > declaration. If you like, declaration is automatic > when the variable is first reference. > > So Sup is declared. Class variable @@x is referenced > and associated with Sup. > > Sup1 is declared. @@x is referenced. @@x is not > found in the current class, so super.@@x is > referenced. > @@x is found, and updated. I think it's simpler than that: you're just assigning to a variable. It's like: x = "A" # ... x = "B" @@x is simply the same variable both times -- that's how it's scoped. > Note thae @@x = "B" is part of the classes > declaration, and so will always be invoked, and that > the 'message' will be passed back to Sup, thus > updating the value of @@x in Sup. > > Same thing happens all over again in Sup2. > > Here is the code to get the desired result. > > class Sup > @@x = nil > writer: @@x There no such thing: $ ruby cvars.rb cvars.rb:3: syntax error writer: @@x ^ [...] > So whats the best approach in ruby? To keep a class > hash that contains a value associated with each class? Over on IRC (irc.freenode.net, channel #ruby-lang) we've just been chatting about class instance variables, which are the best way to achieve true per-class state maintenance. They've been talked about here a number of times; you can search on www.ruby-talk.org or Google. Or join us on IRC :-) David -- David Alan Black home: dblack@superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav