From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2001-08-12T06:23:56+09:00 Subject: [ruby-talk:19547] Re: the way class variables work In article , David Alan Black wrote: >Hello -- > > >But I'm still baffled, maybe more than ever, by the "why", that is, >why class variables exist at all in Ruby. No one seems to have >anything good to say about them. They seem to operate as a kind of >not-quite-global global. They introduce weird, backwards >dependencies. They come to your house at night, ring the doorbell, >and run away. They.... [Cut to shot of David cowering in corner] It is kind of troubling, however, as I thought about it, in practice it isn't generally an issue. For example, the 'classic' use of a class variable is to keep track of how many objects of a certain class exist. In cases like this, the superclass (or parent class, or whatever you want to call it) always exclusively manipulates the class variable. For example: class Vehicle @@number_of_Vehicles = 0 def initialize @@number_of_Vehicles += 1 #increment number of vehicles end end class Bicycle < Vehicle @@number_of_Bycycles = 0 def initialize super @@number_of_Bycycles += 1 end end class Car < Vehicle @@number_of_Cars = 0 def initialize super @@number_of_Cars += 1 end end (actually, I think there are other ways to determine how many objects of a given class exist in Ruby, so in reality one may not do this) Of course this is just a convention that one follows, you could still access @@number_of_Vehicles within Class Car, but you avoid doing so because "it wouldn't be prudent". Is there anyway to apply private access control to class variables? (if not, should there be a way?) Should there be a way to say: class Vehicle private @@number_of_Vehicles = 0 public def initialize @@number_of_Vehicles += 1 end end class Car < Vehicle def initialize super #now try to change @@number_of_Vehicles @@number_of_Vehicles += 10 #<-- this would generate an access error end end The proposed behavior would be that the line that trys to modify @@number_of_Vehicles in class Car would generate an access error. (BTW: this class declaration for Vehicle with the private @@number_of_Vehicles actually 'compiles' and runs for me without any problems - but I can still change the value of @@number_of_Vehicles in the subclass car) Is it worthwhile to add this kind of behavior? Phil