From: Patrick Bennett Date: 2003-08-22T13:59:54+09:00 Subject: Re: Class variables - a surprising result Dan Doel wrote: > > @variables are only like C++ instance variables when used within > instance methods. If you do: > > class Foo > @var = 6 > def Foo.print > p @var > end > > def print > p @var > end > end > > Then: > > Foo.print # => 6 > Foo.new.print # => nil Geesh - sneaky stuff.. This kind of thing *definitely* violates the P.O.L.S. imo. For one, having the 'same' variable actually be two different 'instances' (one, a class variable effectively, and another, an instance variable) is very confusing. I understand it now (although I have to think about it for a sec, and personally, I think that's a bad sign). I think the above @var=6 assignment outside of a method decl should be illegal. It should have to be a @@ reference. > If you want to access these in instance methods, you need to do: > > class Foo > def instance_meth > p self.class.class_eval { @var } > end > end Cool - and interesting, but if I ever saw this in somebody's code, well.... let's just say I'd give them a stern look. ;) > ... > > So it is effectively a class instance variable, although that's still > not the same as a Java static > variable, since it's not inherited. Still not the same. ;)