Hi –
Hi Greg,
Thanks for your help. In fact the question was a little bit different: you can
define IN A CLASS what’s Guy called “class instance variables”. I was stunned
by this a few days ago, as I was assuming too that there are only “class
variables” and “instance variables”, the ones you described.
Class instance variables seems to be a third kind of animal:
variables stored in the class (not in it’s instances), and who does
support the following construct:
[This may overlap with other stuff that’s been posted, but, well, here
it is :-]
The term “class instance variable” is useful but potentially
misleading, because it makes them sound like a special case. In fact,
they are just instance variables, belonging to a particular object.
There’s no third animal involved
Let’s say you did this:
s = String.new(“hello”)
s.instance_eval { @var = 100 }
Now the object s has an instance variable. That variable can only be
seen when self == s, which we can achieve with instance_eval:
s.instance_eval { puts @var } # 100
@var is not available to any string, just to s:
“some other string”.instance_eval { puts @var } # nil
The exact same thing happens with classes. You can perhaps see this
more clearly if we use the same syntax:
c = Class.new
c.instance_eval { @var = 100 }
c.instance_eval { puts @var }
We’ve defined an instance variable on an object. It just happens to
be a Class object. We can do the same test, to show that @var is not
an instance variable of any Class object, just this one:
Array.instance_eval { puts @var } # nil
And there’s a further test we can do, if we want – namely (since this
is a Class object) to examine an instance of the class:
c.new.instance_eval { puts @var } # nil
Our instance of c (c.new) is a different object from c itself.
Therefore, it does not share c’s instance variables. No two objects
share instance variables.
And you can also see that though c happens to be a Class object,
whereas our first example, s, was a String object, the behavior is
exactly the same.
The only difference is in writing style and syntax, because (in spite
of being “just objects”) classes do get some special syntax. Class
definitions are usually written like this:
class Thing
…
end
But inside that block (at the top level, outside of any 'def’s),
‘self’ is set to Thing. So it’s a lot like writing:
Thing = Class.new
Thing.instance_eval { … }
So there’s certainly special syntax associated with class definitions.
But it’s just a front-end to getting into the ‘self’ scope of an
object – an object of type Class – which is really much the same as
getting into the ‘self’ scope of any other object (with
instance_eval).
David
···
On Fri, 6 Dec 2002, Francois Goret wrote:
–
David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav