From: Matthew Harris Date: 2007-12-25T01:21:57+09:00 Subject: Re: Problem with copying array jbieger@gmail.com wrote: > Thanks for your reply! > > Like I said, it's a multidimensional array, so I suppose that the > contents aren't primitive and I need to do as you suggested. Is there > a built-in function for this, or do I need to make my own. It seems > like a pretty common operation... > > Jordi > > On 24 dec, 16:50, Bryan Duxbury wrote: > >> What's your array an array of? Array.dup will copy the array to a new >> array, but if the values in the array are references to some class >> you're using, it'll be a different array of the same items. >> Primitives would be copied correctly. You need to do your own deep >> copy if it's a more complicated array value. >> >> -Bryan >> >> On Dec 24, 2007, at 7:19 AM, jbie...@gmail.com wrote: >> >> >>> Hi, I'm a total newbie with Ruby and I was trying to make this >>> function that would get a (multidimensional) array, make a copy, make >>> some changes to the copy and then return the copy, without altering >>> the original array. However, no matter what I try, the original array >>> gets altered. Here is my code: >>> >>> def prune_times (times) >>> # copy = times >>> # copy = Array.new(times) >>> # copy = times.clone >>> copy = times.dup >>> copy.each do |map| >>> map.each do |task| >>> task.replace(best_n(task, 2)) >>> end >>> end >>> return copy >>> end >>> >>> Any help would be greatly appreciated! >>> >>> Jordi >>> > > > > Your methods of copying the array are correct (though, you should remove one and only use the other, which ever). The problem is that with some objects, Ruby doesn't know how to "copy" them. Bryan already mentioned this, but for primitives like strings, integers, floats and whatnot, Ruby knows how to copy these objects, but if you have custom classes or other classes that don't define their own behavior for copying, then Ruby will keep the reference. Hope that helps. -- Matthew Harris http://matthewharris.org