Am I misunderstanding something, or can you not give a child class a class
variable with the same name as a parent class? Just curious.
Right, class variables are “tree scoped”, meaning that they’re accessible
downwards from the point in the class hierarchy they were first
assigned:
batsman@tux-chan:/tmp$ expand -t2 /tmp/ax.rb
class A
def foo= o
@@foo = o
end
def foo
@@foo
end
end
class B < A
def bar= o
@@foo = o
end
def bar
@@foo
end
end
a = B.new
a.bar = ‘bar’
puts a.bar
a.foo = ‘foo’
puts a.foo
puts a.bar
a.bar = ‘bar’
puts a.foo
batsman@tux-chan:/tmp$ ruby /tmp/ax.rb
bar
foo
/tmp/ax.rb:16: warning: class variable @@foo of A is overridden by B
bar
/tmp/ax.rb:13: warning: class variable @@foo of A is overridden by B
foo
It seems to work as one would expect for constants, but obviously one couldn’t
use a constant to keep track of information.
You can get the desired behavior with class instance variables:
batsman@tux-chan:/tmp$ expand -t2 /tmp/aw.rb
class Parent
@count = 1
class << self; attr_reader :count end
def parentCount
Parent.count
end
end
class Child < Parent
@count = 2
def childCount
Child.count
end
end
p = Parent.new
c = Child.new
puts p.parentCount
puts c.childCount
puts c.parentCount
batsman@tux-chan:/tmp$ ruby /tmp/aw.rb
1
2
1
···
On Thu, Jun 19, 2003 at 09:17:48AM +0900, Zellyn Hunter wrote:
–
_ _
__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_
_ \ / ` | ’ \
) | (| | |__ \ | | | | | (| | | | |
.__/ _,|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com
MSDOS didn’t get as bad as it is overnight – it took over ten years
of careful development.
– dmeggins@aix1.uottawa.ca