Marcin Mielzynski
7/10/2006 12:53:00 AM
anne001 wrote:
>
> I thought of an instance as a copy of the class. so implicitely I
> assumed it would get a copy of an instance variable. Maybe I should
> think of an object as an inheritance of methods: So it inherits
> methods, not variables.
>
Instance of a class is not a copy of it. Classes are somewhat templates
for instances, they define what methods and variables their instances
will have. But since a Class in Ruby is also an object it can have
instance variable as well!.
>
> In class C, running x adds @var to the object,
As it should do
but in D, running x does
> not add @@var.
@@var is a special variable that is shared between class and it's
instances (so there is only one @@var, no matter how many instances
there are).
>
> @var is an instance variable that belongs to whatever object is
> "self" at that moment in runtime.
No, self is different in class context and instance context.
>
> QUESTION: If that is the case, why does puts self not append @var=1 to
> object C the way it
> appends @var=2 to the instance?
> #<C:0x25b58 @var=2>
Class objects have different default implementation of inspect method,
so they are printed differently using p. There is a way to query object
about their variables:
p C.instance_variable_get("@var")
-> 1
p y.instance_variable_get("@var")
-> 2
> In any case, the code in C outside of the methods is only run once when
> the new method is called, and the object is C. OK. I had not thought of
> it that way.
>
> So is this an ok way to think about objects:
> 1. Objects inherit methods
Nope, classes define methods which in turn will be available to their
instances upon construction
> 2. The variable environment includes, read access to Class constants,
> r/w to @@var and r/w to global variables
Again, depends on the context (receiver aka self)
> 2. @var become local to whatever object is self at the moment they are
> created.
I've never considered instance variables to be local to their instances
- but in a way, yes.
lopex