From: Robert Klemme Date: 2005-07-03T21:50:43+09:00 Subject: Re: class variable leading a double life James Edward Gray II wrote: > On Jul 2, 2005, at 3:05 PM, Devin Mullins wrote: > >> OK, now I'm confused. I had thought that class variables were just >> instance variables of the Test object, but it seems that the case >> is much weirder than that. (Why?) > > We already have a syntax for instance variables, so that's what you > use if you want an instance variable on test. The reason class > variables don't work like that is that they would then by tricky to > reach fro instance objects of the class and that wouldn't be good at > all. Let me add to that that usually you want to associate a variable with the class instance or with instances. Class variables (the ones with @@) have some strange properties that sometimes lead to surprising behavior. I generally recommend to not use them. Instance variables in classes are much simpler to handle and much clearer and cleaner IMHO. Just a simple example where each new instance gets assigned a serial number: class Foo @cnt = 0 def self.tick() @cnt += 1 end attr_reader :serial def initialize @serial = self.class.tick end end ?> instances = (1..10).map { Foo.new } => [#, #, #, #, #, #, #, #, #, #] >> instances.map {|f| f.serial} => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Note that this has to be changed slightly if you want to inherit from Foo. I just didn't want to make this overly complicated. Kind regards robert