From: Robert Klemme Date: 2005-07-04T06:35:44+09:00 Subject: Re: class variable leading a double life Devin Mullins wrote: > Robert Klemme wrote: > >> Class variables (the ones with @@) have some strange properties that >> sometimes lead to surprising behavior. > > Indeed. I figured out why my code sample didn't work. Ruby considers > it a "toplevel singleton method." If I define a class method inside > the class definition, it works, but if I define it outside (as I did > in my email), it's looks to the closest class definition outward -- > in this case, the thing irb wraps my code in. This is one of those > odd cases where irb acts differently from Ruby-raw, too. Also, Ruby > didn't warn me about toplevel singleton access like they said it > should. I noticed it does, though, if I use class << Test syntax. > > This make sense, now. def Test.blah is a singleton method, and Ruby > doesn't know anything about class scope when it's looking at this > definition, because it's treating Test like any old object on which to > define a singleton method. It needs to be stuck inside a class > Blah...end block to know where the class variables lie. > > Still icky, though. (See below for my RCR-lite.) > >> 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: > > Thanks for the example. I'm just wondering why > > class Foo > def blah > @@cnt += 1 > end > end > > couldn't have been a shortcut for [an optimization of]: > > class Foo > class << self > attr_accessor :cnt > end > def blah > self.class.cnt += 1 > end > end > > And why instead class variables were done the way they were. > > And if I don't get a decent answer, I'll go complain about it in my > imaginary blog! So take that, matz! > > Devin As far as I remember even Matz agrees that class variables are awkward. I think they are on their way out - at least in Ruby 2. Btw, for extra fun mix inheritance with class variables and change the order in which they are defined between super and sub classes! :-) Regards robert