From: "David A. Black" Date: 2009-11-30T06:21:10+09:00 Subject: Re: Class variables, instance variables, singleton; Ruby v. C++ Hi -- On Sat, 28 Nov 2009, Ralph Shnelvar wrote: > DAB> And of course this is one of the (many) problems with class variables: > DAB> they make obscure the otherwise rather simple notion that classes can > DAB> have instance variables because classes are objects and any object can > DAB> have instance variables. > > David ... this may be the higher-level gestalt that I was missing. It > sure sounds like it. I have often made the observation that the answer to 75% of all questions about Ruby is: "Because classes are also objects." :-) Rick has explained most or all of what you were asking about. With regard to class variables, I would encourage you to keep them somewhat separate in your mind from the rest of the Ruby object and variable/identifier model. Class variables are kind of layered on top, as an expedient for getting class objects and their instances to share data. Since classes are objects and their instances are *different* objects, having them share data via variables is just a variation on the theme of global variables; indeed, class variables are essentially hierarchy-scoped globals. Instance variables are a completely unrelated and totally different matter: they are the mechanism for per-object state. Every object has its own supply of instance variables, and by definition, no object can see the instance variables of any other object -- even if object 1 is a class and object 2 is an instance of that class. This is enforced via the "self" mechanism: whenever you see an instance variable, you are seeing an instance variable that belongs to self (whatever self is at that moment). I've always felt that it's unfortunate that class variables start with "@@", because that conveys the impression that they're somehow akin to instance variables. They're not; they're actually kind of the opposite of instance variables, because they exist in order to blur the borders between objects rather than to clarify them. They really should have been "$$var" :-) Many of us would not mourn them if they disappeared from Ruby. David -- THE COMPLEAT RUBYIST, Ruby training with Black/Brown/McAnally! January 22-23, Tampa, Florida Info and registration at http://www.thecompleatrubyist.com -------------------------------------- My new job: http://tinyurl.com/yfpn9hz