Class variables in parent and child classes with the same name

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.

It seems to work as one would expect for constants, but obviously one couldn’t
use a constant to keep track of information.

[Note that ruby -w catches the redefinition]

Zellyn

class Parent
Version = 1
@@count = 1

def printCount
puts @@count
end

def printVersion
puts Version
end
end

class Child < Parent
Version = 2
@@count = 2

def showCount
puts @@count
end

def showVersion
puts Version
end
end

p = Parent.new
c = Child.new

c.printCount # => 2
c.showCount # => 2
p.printCount # => 2

c.printVersion # => 1
c.showVersion # => 2
p.printVersion # => 1

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

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.
You can, however each class shares it’s class variable with it’s
ancestors, the alternative is class instance variables:

class Parent
def self.counter()
@count
end
end

Be aware that class instance variables are not inherited(Parent and Child
will have different counters)

···


Idan