From: Marnen Laibow-Koser Date: 2009-11-28T22:33:51+09:00 Subject: Re: Class variables, instance variables, singleton; Ruby v. Ralph Shnelvar wrote: [...] > Let me flesh out my questions/comments about this paragraph so that you > and > others have something specific to answer. Let's call the classed F & > G. > > (1) OK, classes are (i) objects; Right. > (ii) are executable code. Wrong. Class *definitions* are executable code. > > > (2) If I do the following > class F > end > f = F.new > F.class # class > f.class # F > this makes sense to me. > > What (relevant and important conceptually) messages (other than "new") > can I send to a class? See the documentation for class Class. > But see (3), below. > > > > (3) > class F > def sub1 > @@x = 1 > end > end > > class G > self.sub1 > @@x=2 > end > end > > # Why? Didn't the interpreter "see" @@x in class F? > F.class_variables # [] Probably not, since you haven't called the function yet! > > # makes sense > G.class_variables # ["@@x"] I'm actually rather surprised by this. > > f = F.new > > # Why? Shouldn't the method inherit from the class? > f.class_variables # undefined method No! class_variables is a class method of F. Instances do not get access to their class' class methods, because they don't inherit from the Class object in the conventional sense. The Class object is a little bit like a JavaScript prototype, if that helps. If it doesn't...well, I don't know what to say. If you're really as good a C++ programmer as you claim to be, then you should be having no trouble at all with the difference between class and instance methods. > > f.sub1 # 1 > > # makes sense. class variable now explicitly executed > F.class_variables # ["@@x"] > > # How to use class_variable_get if the method is private??? > F.class_variable_get(:@@x) # error private method! > Just don't. You're not meant to be getting at class variables from outside the class. Use an accessor function if you need it. (There is a way to call private methods from outside, but I will leave you to find it out on your own. It's not generally a good thing, and I'm not going to hand you a dangerous tool until you understand when not to use it.) > > > OK, that should do it for now. Best, -- Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.