A question about class variable

S

Sam Kong

Hello!

I have a question about class variable.

class C1
@@a = "C1"
def f
@@a
end
end

class C2 < C1
@@a = "C2"
end

puts C2.new.f #=> "C2"

It's understandable.
When I called C2.new.f
the method f seems to find C2's @@a.

Now I removed @@a from C1.

class C1
def f
@@a
end
end

class C2 < C1
@@a = "C2"
end

puts C2.new.f
#Result: in `f': uninitialized class variable @@a in C1 (NameError)


Why does it bother with C1's @@a if it returns C2's @@a?
I assume that the method f should behave polymorphically and the body
of f should be interpreted in the context of C2's instance method if I
call it via an instance of C2.
Probably I misunderstand something.
Can anybody enlighten me on this?

Thanks in advance.
Sam
 
S

Sean O'Halpin

Hello!

I have a question about class variable.

class C1
@@a =3D "C1"
def f
@@a
end
end

class C2 < C1
@@a =3D "C2"
end

puts C2.new.f #=3D> "C2"
If you add the line:

puts C1.new.f #=3D> "C2"

you'll see that the @@a you set in C2 is actually the same @@a as
defined in C1. Class variables in Ruby 1.8.2 are a more like 'class globals=
'.
All subclasses share the same variable.
I assume that the method f should behave polymorphically and the body
of f should be interpreted in the context of C2's instance method if I
call it via an instance of C2.

Ah assumptions! ;) The body of f ~is~ interpreted in the context of
C2's instance, but the @@a is scoped to the class in which f is
~defined~.

HTH

Regards,

Sean
 
D

David A. Black

Hi --

class C1
def f
@@a
end
end

class C2 < C1
@@a = "C2"
end

puts C2.new.f
#Result: in `f': uninitialized class variable @@a in C1 (NameError)


Why does it bother with C1's @@a if it returns C2's @@a?

Class variables are per-hierarchy, as you've seen, but if you create
one down the hierarchy, it does not get propagated upward. So C1 has
no @@a, even though @@a was initialized in its subclass C2.

Matz described this in ruby-talk 19774 as "an error that Ruby does not
detect yet." I was never sure if he meant a programmer error, or a
Ruby error :) Anyway, it's a bit of an anomaly.

In any case, class variables are likely to change greatly in Ruby 2.0,
becoming class/module-scoped rather than hierarchy scoped.


David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top