Treatment of class variables in inherited classes


(Gray, Jeff) #1

From: David Alan Black [mailto:dblack@candle.superlink.net]

class Box

@@stuff = {:e => 1} # intentionally commented out

def Box.add(k, v)
@@stuff[k] = v
end

[…]

Crate.add(:d, 4)

Don’t you get an “uninitialized class variable” error at that point
(if line 2 is commented out)?

Actually, the code runs without error on our site installation
of Ruby, which is v1.6.5. Only Box.add elicits the error with
line 2 commented out, as one would expect. But on my local build
of v1.6.7 (and 1.7.2), Crate.add does evoke the uninitialized class
variable error. Kinda makes my whole post moot… D’oh!

But I guess my initial instinct – that the way v1.6.5 behaved
seemed strange – was in fact justified…

If you want real per-class variables, you can create instance
variables for your classes:

Thanks, I had never considered that possibility!

Cheers,

  • jeff

(David Alan Black) #2

Hello –

From: David Alan Black [mailto:dblack@candle.superlink.net]

class Box

@@stuff = {:e => 1} # intentionally commented out

def Box.add(k, v)
@@stuff[k] = v
end

[…]

Crate.add(:d, 4)

Don’t you get an “uninitialized class variable” error at that point
(if line 2 is commented out)?

Actually, the code runs without error on our site installation
of Ruby, which is v1.6.5. Only Box.add elicits the error with
line 2 commented out, as one would expect. But on my local build
of v1.6.7 (and 1.7.2), Crate.add does evoke the uninitialized class
variable error. Kinda makes my whole post moot… D’oh!

Hmmm… I only get the error on 1.6.7… but anyway, I don’t think
your post is moot, because the thing with class vars not being/not
being the same object for subclasses still seems to be the case, and
it’s good to know about.

Here’s a simplified example, just for playing around with:

Assignments

class A

@@cvar = “assigned in A” # commented out (see below)

end

class B < A
@@cvar = "assigned in B"
end

class A
@@cvar = "assigned in A"
end

Inspection

class A
puts @@cvar # assigned in A
end

class B
puts @@cvar # assigned in B, but A if line 2 is uncommented
end

David

···

On Wed, 3 Jul 2002, Gray, Jeff wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav