From: Michael Neumann Date: 2003-05-21T17:59:15+09:00 Subject: Re: Copying an Array On Wed, May 21, 2003 at 05:24:13PM +0900, Frederic Chalons - Design Support IA Student wrote: > Hi, > > The = operator seems to retrieve an reference on a Array rather than > copying what it contains > as in the following code: > ******* > a = [1,2,3] > b = a > > p b.id; p a.id > b.each_index do |i| > b[i] *= 2 > end > ******** > both a and b equals to [2,4,6] > > This can be solve by using a.collect or a.dup but the problem would > occur again if a,b are multi dimensions Array. dup or collect reference > on the sub-Array? > Isn't there a clean and consise way to copy the whole content of an > multi dimension Array so that the copy is not somehow linked to the > original. Use Marshal: def deep_clone(anObj) Marshal.load(Marshal.dump(anObj)) end > Btw, a would be modified even though it is accessed as attri_reader. You can modify the arrays content, but you cannot assign a new object to a (@a). > So I guess = is copying the pointer rather than any content (a.id == b.id) = is just a reference assignment, does not copy anything except the pointer at all. Note that []= or obj.a= are methods and not an assignment! a = [1,2,3] a[0] = 2 # This is no assignment! It's a method call! Regards, Michael