Hi,
Why cant i have an attribute reader for a class variable.
Class variables are shared among many objects (the class, its
subclasses, all instances of all those classes), so they're not really
the right choice for representing an "attribute", which is generally
understood to be a property of a particular object.
You can certain write wrapper get/set methods around class variables,
and even automate the process. You can also give your classes their
own attributes; since classes are objects, they can have attributes
like other objects. To do that, you need to call attr_* in the
context of the class's singleton class:
______________________________________________
LLama Gratis a cualquier PC del Mundo.
Llamadas a fijos y móviles desde 1 céntimo por minuto. http://es.voice.yahoo.com
David, technically is there any relationship between the attribute @x here
class A @x = 1
end
and the @x that accessor deals with? That would be an attribute of what? Is there a singleton instance of the singleton class? Or is that @x an attribute of A as instance of Class? I tried to get this right with examples but I guess the exact answer comes from the actual implementation.
-- fxn
fxn@feynman:~/tmp$ cat foo.rb
class A @x = 0 @y = 1
class << self
def x @x
end
attr_accessor :y
end
end
puts A.x, A.y
fxn@feynman:~/tmp$ ruby foo.rb
0
1
···
On Nov 16, 2006, at 1:01 PM, dblack@wobblini.net wrote:
David, technically is there any relationship between the attribute @x here
class A @x = 1
end
and the @x that accessor deals with?
Yes; they're the same @x.
That would be an attribute of what? Is there a singleton instance of
the singleton class? Or is that @x an attribute of A as instance of
Class? I tried to get this right with examples but I guess the exact
answer comes from the actual implementation.
@x is an instance variable of A. The accessor methods are defined for
A only, not for all classes. In general, when you do this:
class << obj
...
end
you're in the singleton class of obj, and whatever instance methods
you define are singleton methods of obj. attr_accessor is just a
mechanism for writing instance methods. So what I did was equivalent
to:
class A
class << self
def x @x
end
def x=(y) @x = y
end
end
end
i.e., adding instance methods to A's singleton class.
David
···
On Fri, 17 Nov 2006, Xavier Noria wrote:
On Nov 16, 2006, at 1:01 PM, dblack@wobblini.net wrote: