From: Ryan Pavlik Date: 2003-08-22T14:19:12+09:00 Subject: Re: Class variables - a surprising result On Fri, 22 Aug 2003 13:59:54 +0900 Patrick Bennett wrote: > Dan Doel wrote: > > 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. Definitely not. One of the coolest things about ruby is that when you say "class" or "module", it doesn't open a declarative section of code, but rather an new executive section. This helps greatly in eliminating special syntaxes. For instance: class A attr_accessor :a, :b private def foo; ... end end In this case, "attr_accessor" and "private", which would regularly be syntax, are actually method calls. This is Very Cool: class Module def def_abstract(*args) for sym in args module_eval <<-CODE def #{sym}(*args); raise SubclassResponsibility; end CODE end end #m:def_abstract end #c:Module Now I can do: class B def_abstract :foo, :bar end Nifty! In fact, I've used this to define new attr_* functions, and a few other things, to make life easier: class C attr_accessor_typed String, :title, :text end The fact that a class or module body is just code along with everything else gives great flexibility. As for @instance variables of Class being confusing... it's not at all. It's like this: # <--- Over here we have a Class object over here we have a D object -----> # If you think of everything being an object, the proper place to put your "static" variables is in the Class object itself. It's a matter of understanding the proper way to think about Ruby, rather than trying to translate it into something else. -- Ryan Pavlik "Let super-dimensional physics take its course!" - 8BT