rocky.stevens
7/5/2007 5:50:00 PM
I am just starting Ruby, and am a bit confused about how class-level
methods and variables are implemented. I had expected them to be
implemented the same way as an instance method/variable on the the
specific class object itself. For example, I thought static1 and
static2 would be implemented the same way below:
-------------------------------------------------
class C1
@@static1 = "@@static1"
def C1.static1
@@static1
end
end
C1.instance_eval do
@static2 = "@static2"
def static2
@static2
end
end
---------------------------------------------
Now, when I call C1.static1 and C2.static2, I get "@@static1" and
"@static2", respectively. So far, so good. But if I make an empty
class C2 which derives off of C1, then C2.static1 and C2.static2
resolve to "@@static1" and nil, respectively.
So it seems to me that when a class tries to access a "@@" variable,
Ruby keeps going up the self.superclass chain until it finds it. But
if the class object itself has a "@" variable, this is not done.
All this would be easy to accept, except for the fact that this does
not seem to apply to methods: C2.static2 was a perfectly valid method,
even though I only defined it for C1.
So I guess my question is, have I correctly interpreted the behavior I
am seeing? Am I missing something?