From: Dan Doel Date: 2003-08-22T15:43:31+09:00 Subject: Re: Class variables - a surprising result Patrick Bennett wrote: > Geesh - sneaky stuff.. It can get sneakier. There's more than one way to make a class instance variable in ruby; two useful, and two useless. class Foo @class_instance_var1 = "I am variable 1" class << self @class_instance_var2 = "I am variable 2" end def make3 class << self class << self @class_instance_var3a = "I am variable 3a" end @class_instance_var3b = "I am variable 3b" end end self.class.class_eval { @class_instance_var4 = "I am variable 4" } end Okay: #1 is an instance variable of the Foo class object. It's accessed from instance methods like so: self.class.class_eval { @class_instance_var1 } Also, you can use #attr methods to make accessors for you like so: class Foo class << self attr_accessor :class_instance_var1 end end #2 is an instance variable of the singleton class of Foo. This is the type of class instance variable created when you do: class << self.class ... end In an instance method. These are separate from #1 type class instance variables, so you can't mix and match the two. To make an accessor for this, you do: class Foo class << self class << self attr_accessor :class_instance_var2 end end end #3 has two variables, but they're equally useless. Essentially they're the two different flavors shown above, but instead of using the Foo class object, you're using the singleton class of an instance of Foo. This essentially makes them no better than instance variables, unless you capture the singleton class and make new instances with it, in which case you should be able to access them using the methods in #1 and #2. #4 is the same as #2, except that it uses Foo's formal class, which is Class. This makes @class_instance_var4 available to all classes, which is probably undesireable. I'm not sure which of #1 or #2 is more accepted/useful/whatever. There probably isn't a concensus, since I don't think this comes up a whole lot. Are we confused yet? :) - Dan