From: dblack@... Date: 2006-12-22T10:56:59+09:00 Subject: Re: Class Variable Confusion Hi -- On Fri, 22 Dec 2006, gwtmp01@mac.com wrote: > class A > @@avar = "hello" > end > @@avar = 1 > > A.class_eval { puts @@avar } # => 1 > class A > puts @@avar # => hello > end > > There are now two distinct class variables named @@avar, one is associated > with Object and another is associated with class A and shadows the one > associated with Object. Yes -- basically, if you create the class variable in the subclass first, then it's different from the one in the superclass. Mind you, a lot of this is scheduled to change in 2.0. I fear, though that the confusion caused by class variables will persist. A class variable is going to be (as I understand it) more similar to an instance variable than it is now, but with visibility to instances of the class. A lot of the problem with class variables is that they cloud the matter of classes being objects and having their own instance variables. I'm not sure whether these changes will change that. (When I say they cloud it, I'm basing this on six years of watching person after person after person have trouble grasping this area of Ruby, and it's always something like, "Wait -- doesn't a class have *class* variables? If they're analogous to instance variables for instances, then what are they?" It can be explained, of course (I've done it many times :-) but there's definitely something in the behavior that makes this harder to get than most other language features.) > I still don't understand why class_eval/instance_eval don't affect the > resolution of class variables in a manner analogous to how they affect the > resolution of instance variables. Is this by design or accident? See David Goodlad's explanation; I think it's by design. class_eval brings about a scope that's like a 'class' block in some ways but not in others. The surrounding class and local variables can permeate their way in. David -- Q. What's a good holiday present for the serious Rails developer? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) aka The Ruby book for Rails developers! Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)