Eero Saynatkari
10/23/2006 4:39:00 PM
On 2006.10.23 20:25, John Turner wrote:
> Diego Virasoro wrote:
> >>Please explain. Use an example.
> >
> >>From what I understood, for any instance variable, I can make ruby
> >automatically produce the accessors. For example:
> >
> >class Dog
> > @name
> > @@NumberOfLegs = 4
> >
> > attr_accessor :name
> >end
> >
> >x = Animal.new
> >...
> >puts x.name
> >
> >
> >However, I would like to do something similar for class variables. So
> >for example in the above example, for @@NumberOfLegs.
> >
> >Is this possible?
> >
> >Thank you
> >
> >Diego Virasoro
> >
>
> You can do this for instance variables of a class, not sure there are
> equivalents for actual class variables though:
>
> class Dog
> @names = ["Fido", "Rex"]
> class << self
> attr_accessor :names
> end
> end
> puts Dog.names
Please note that it is often better to use class instance variables
(@var at the class scope) rather than class variables (@@var):
class A; @@a = 5; end
class B < A; @@a = 4; end
class C < A; @@a = 3; end
class D < B; @@a = 2; end
p A.send 'class_variable_get', "@@a"
p B.send 'class_variable_get', "@@a"
p C.send 'class_variable_get', "@@a"
p D.send 'class_variable_get', "@@a"
class C; @@a = 4; end
p A.send 'class_variable_get', "@@a"
p B.send 'class_variable_get', "@@a"
p C.send 'class_variable_get', "@@a"
p D.send 'class_variable_get', "@@a"
Class instance variables have a simpler inheritance, none:
class E; @a = 1; end
class F < E; end
p E.send 'instance_variable_get', '@a'
p F.send 'instance_variable_get', '@a'
class F; @a = 2; end
p E.send 'instance_variable_get', '@a'
p F.send 'instance_variable_get', '@a'