zig wrote: > I'm still learning my way around ruby and I seem to be confused about > class methods/variables versus instance methods/variables. My example > comes from Ruby on Rails, but I don't think my confusion is rails- > specific. > > In ActiveRecord::Base, there is a method columns. I initially thought > this was an instance method since it wasn't declared as > ActiveRecord::Base.columns, which is the required syntax for class > methods. However someone explained to me that you can enclose several > method declarations in a class << self block which makes them all > class methods. > > OK, so columns is a class method. But then in its source, it makes > reference to the instance variable @columns. In other OOP languages > that I'm familiar with, it's forbidden to access instance variables > within a class method (if the class hasn't been instantiated, then the > instance variables can't have been initialized). I've investigated > the situation in ruby, and apparently it is this: it's not illegal to > reference an instance variable from within a class method, but the > instance variable will be nil. Not quite. The difference between Ruby and other languages is that *the class itself is an object*. This means that when you refer to an instance variable in a class method, you're referring to an instance variable of the class object itself, not the instance variable of any instances of that class. > In the rails scaffolding, the code calls Modelname.columns. So it's > calling the class method, and the class has not been instantiated. > > Help de-confuse me! How does this class method get away with > referencing an instance variable and where exactly does this instance > variable get initialized? (I can't find any occurrences of @columns > outside of other class methods, so it's apparently not being > initialized anywhere in this class?) In this case, it's an instance variable on the Modelname class which, as I rather confusingly explain above, is also an object - it's an instance of class Class. Clear as mud? :-) -- Alex