From: Leslie Viljoen Date: 2008-07-04T05:40:19+09:00 Subject: Re: How to duplicate elements in array? On 7/3/08, Chris Chris wrote: > Hi, > > something I couldn't quite figure out (sorry for posting so soon after > my last question)... > > a = [["ABC", "30", "1"]] > > I want to duplicate/copy the element. This is what I'm trying to get: > > a2 = [["ABC", "30", "1"], ["ABC", "30", "1"]] > > What I did was simply > > a2 = a + a > > => [["ABC", "30", "1"], ["ABC", "30", "1"]] > > That works. > > I then tried changing a single element. > > a2[0][1] = "test" > > puts a2.inspect > => [["ABC", "test", "1"], ["ABC", "test", "1"]] > > Of course, I just intended to change the first value, not both of them. > > > Can anybody explain please what I can do about this? You need to use .dup: >> a = ["ABC", "30", "1"] => ["ABC", "30", "1"] >> b = a.dup => ["ABC", "30", "1"] >> b[0] = "DEF" => "DEF" >> a => ["ABC", "30", "1"] >> b => ["DEF", "30", "1"] If you just assign an object, you get another reference to the same object. DUP will give you a copy, although not a deep copy. That means that if a = [["ABC", "30", "1"]], a.dup will not give you a copy of the element within the array - it will give you a copy of the array with the inner element being a reference again: >> a = [["ABC", "30", "1"]] => [["ABC", "30", "1"]] >> b = a.dup => [["ABC", "30", "1"]] >> b[0][0] = "DEF" => "DEF" >> a => [["DEF", "30", "1"]] >> b => [["DEF", "30", "1"]] The easy way to do deep copies is to use Marshal. Les