From: Rick DeNatale Date: 2008-09-18T22:01:35+09:00 Subject: Re: why one array continues to grow after repeated call ------=_Part_36016_18091937.1221743351353 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Thu, Sep 18, 2008 at 8:41 AM, Li Chen wrote: > Hi all, > > I write a script for studying purpose: > create a new array(b1) based on an existing one (a1). > > I expect that once an array is set up it should be fixed regardless how > many times it is called. But I find array b1 continues to grow if I call > it repeatedly? I can't find an explantion for that. Any idea? > > Thank you very much in advance, > You seem to have a common misperception that assigning a value to a ruby variable acts like a declaration, rather than just a, potentially temporary, binding of the variable to a particular object. > C:\Users\Alex>irb > irb(main):001:0> class A > irb(main):002:1> def initialize > irb(main):003:2> @a1=[] > irb(main):004:2> @b1=[] If instance variables were constrained by the declaration, then @a1 and @b1 would have to always refer to empty arrays. > > irb(main):005:2> method1 And method1 could have no effect here. > > irb(main):006:2> end > irb(main):007:1> > irb(main):008:1* def method2 > irb(main):009:2> (method1.size).times{@b1<<10} What really happens here is that the array referenced by @b1 has @a1.size 10's added each time the method is called. > > irb(main):010:2> return @b1 > irb(main):011:2> end > irb(main):012:1> > irb(main):013:1* > irb(main):014:1* def method1 > irb(main):015:2> @a1=[1,2,3,4] And this line replaces the empty array bound to @a1 in the initialize method with a new array instance. The original empty array is now subject to garbage collection. > > irb(main):016:2> return @a1 > irb(main):017:2> end > irb(main):018:1> > irb(main):019:1* end > => nil > irb(main):020:0> ob=A.new > => # > irb(main):021:0> ob.method2 > => [10, 10, 10, 10] > irb(main):022:0> ob.method2 > => [10, 10, 10, 10, 10, 10, 10, 10] > irb(main):023:0> ob.method2 > => [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] > irb(main):024:0> ob.method1 > => [1, 2, 3, 4] > irb(main):025:0> ob.method2 > => [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] > irb(main):026:0> exit Perhaps this two year old article in my blog might give some insight http://talklikeaduck.denhaven2.com/articles/2006/09/13/on-variables-values-and-objects -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/ ------=_Part_36016_18091937.1221743351353--