Yukihiro Matsumoto
3/27/2007 2:44:00 AM
Hi,
In message "Re: Class Variables for subclases..."
on Tue, 27 Mar 2007 11:37:38 +0900, Sonny Chee <sonny.chee@gmail.com> writes:
|Check out the following:
|
|class A
| @@anobject = 'green'
| def fun2
| @@anobject
| end
|end
|
|class B < A
| @@anobject = 'blue'
| def fun2
| @@anobject
| end
|end
|
|puts B.new.fun2 # blue
|puts A.new.fun2 # blue
|
|So it looks like the subclass B is not defining its own class variable
|but reusing A's class variable @@anobject. Is there a different way to
|specify class variables to overcome this issue?
You can use constants-as-class-shared technique.
class A
Anobject = ['green']
def fun2
Anobject[0]
end
end
class B < A
Anobject = ['blue']
def fun2
Anobject[0]
end
end
puts B.new.fun2 # blue
puts A.new.fun2 # blue