From: "David A. Black" Date: 2005-10-26T03:23:59+09:00 Subject: Re: having reference problems Hi -- On Wed, 26 Oct 2005, shalperin wrote: > Here is a code snippet: > > class Foo > @a > @b > @reference > def initialize() > @reference = [@a, @b] > end > > attr_writer :a, :b, :reference > attr_reader :a, :b, :reference > end > > f = Foo.new() > f.reference[0] = 1 > puts f.a #nil WTF! > > What I am trying to do is refer to an instance variable both by its index in > some array, and also directly. > > Any help would be greatly apreciated. OK, you need to clear some cobwebs :-) First of all, this: @a is just the value of @a. It doesn't do anything; it's essentially a waste of electrons. Second, there's a rule about instance variables that will help you not only here but generally: *Whenever* you see an instance variable (@a or whatever), that instance variable belongs to whatever object is, at that moment, "self" (the current object). If you peek inside a class definition, you'll find that the current object is a class object: class Foo p self # Foo end If you peek inside an instance method definition, you'll find that self is the instance: class Foo def talk p self end end Foo.new.talk # # That means that you're dealing with two completely different scopes, for instance variable (and most other) purposes: class Foo @a = 1 # this @a belongs to the Class object called Foo def initialize @a = 1 # *this* @a will belong to a newly-minted Foo instance end end No two objects share instance variables -- even if one of the objects happens to be an instance of the other object. Like about 3/4 of all Ruby problems, this one comes down to: classes are objects too :-) Third.... when you do this: foo.reference[0] = 1 you are *replacing* the first element of foo.reference with 1. At this point, foo.reference will consist of: [1,nil] # the new 1 value, plus the default value of @b (nil) Both @a and @b will be nil, because you have not assigned to either of them. David -- David A. Black dblack@wobblini.net