From: Robert Klemme Date: 2003-05-21T17:56:37+09:00 Subject: Re: Copying an Array You want a deep copy of a nested array structure. As easy as that: module Enumerable def deep_copy map {|x| x.respond_to?( :deep_copy ) ? x.deep_copy : x} end end a=[[1,2],[3,4]] b=a.dup puts( a.equal?( b ) ) puts( a[0].equal?( b[0] ) ) b=a.deep_copy puts( a.equal?( b ) ) puts( a[0].equal?( b[0] ) ) Yields: false true false false Regards robert "Frederic Chalons - Design Support IA Student" schrieb im Newsbeitrag news:3ECB3715.7000204@st.com... > 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. > > Btw, a would be modified even though it is accessed as attri_reader. So > I guess = is copying the pointer rather than any content (a.id == b.id) > > (using ruby 1.6.8 (2002-12-24) [sparc-solaris2.8]) > > Thank you, > Fred > >