From: zig Date: 2007-03-25T06:50:08+09:00 Subject: class methods and instance variables in ActiveRecord::Base 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. 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?) Thanks in advance, zig