A question about class variable

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

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"

If you add the line:

  puts C1.new.f #=> "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! :wink: 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

···

On 11/10/05, Sam Kong <sam.s.kong@gmail.com> wrote:

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 :slight_smile: 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

···

On Fri, 11 Nov 2005, Sam Kong wrote:

--
David A. Black
dblack@wobblini.net