From: Stefano Crocco Date: 2007-03-25T16:54:57+09:00 Subject: Re: class methods and instance variables in ActiveRecord::Base Alle domenica 25 marzo 2007, zig ha scritto: > On Mar 24, 6:52 pm, Timothy Hunter wrote: > > A class variable is NOT the same as an instance variable of the class > > object. Have you tried "calling" @@var1 with A.var1? It doesn't work. > > The attr_reader and attr_writer methods create methods that operate on > > @var1. There is no method "var1" that operates on @@var1. > > You're right, that method isn't defined in the first case, I've just > tried it. It also fails because class variables are required to be > initialized, which I didn't do. > > So how about this? > > class A > @@var1 = 2 > def A.var1 > @@var1 > end > end > > class A > class << self > @var1 = 2 > def var1 > @var1 > end > end > end > > > I tried this in irb as well, and again, they're not the same, but I > can't figure out why not. This time the first declaration gives > A.var1 => 2, while the second gives A.var1 => nil. But what happened > to my 2? In the second case, you have set @var1 to 2 in the context of the singleton class of A, not in the context of A, so it becomes an instance variable of the singleton class of A, not an instance variable of A. var1, instead is a class method of A, so inside its definition, self is A. Ruby will look for an instance variable called @var1 defined for A, it won't find it and will create a new one set to nil. To make the code work, you only need to move the line @var1=2 above the line class << self. This way, @var1 will become an instance variable of A and everyting will work. Regarding the difference between class variable and class instance variables: they have nothing in common. They can be accessed by instances of the class (and even created in instance methods) and are shared between a class and its descendents. A class instance variable is private to the class, and can't be accessed by the outside unless you provide suitable methods. In other threads on this list, it was suggested that it's best to avoid class variables and use class instance variables or constants instead (I don't know whether this is true or not, I'm only reporting). I hope this helps Stefano