From: Rick DeNatale Date: 2008-09-22T06:59:30+09:00 Subject: Re: Instance variable acting like class variable? ------=_Part_68434_30335978.1222034856501 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Sun, Sep 21, 2008 at 3:47 PM, Mike Mr. wrote: > I've written a Node class that I'm using to write a few programs for in > a course. > > class Node > #... > > def initialize(row, col, cost, direction=nil, parent=nil) > #... @collected = (parent.nil?) ? [] : parent.collected.to_a > end > > > The problem is with #add_collected. When it is called its updating > @collected for all instances of Node. You are confusing the instance variable @collected with the object it references. Every instance of Node will have it's own instance variable, BUT assume that you do n1 = Node.new(r1, c1, cost1, direction1) n2 = Node.new(r2, c2, cost2, direction2, n1) Now since Array#to_a returns self (i.e. the same array), n2.collected will refer to exactly the same array as n1.collected, and so any changes to the object will be visible through either instance variable. If you change the parent.collected.to_a to parent_collected.dup then it will break this alias by making a shallow copy of the parents array at the time of initialization, but, not knowing what you are trying to do, this might or might not fix your actual problem. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/ ------=_Part_68434_30335978.1222034856501--