From: "David A. Black" Date: 2008-10-31T02:55:39+09:00 Subject: Re: Problem with copying array Hi -- On Fri, 31 Oct 2008, Alan Slater wrote: > Highly related newbie question, please pardon the non-technical > language. > > So, arrays (even arrays of 'primitives' like strings) don't actually > contain the objects that fill each entry, they instead (effectively) > link to those objects. So, .delete_at and .slice! (for example) don't > remove things from the array, they delete the objects that are being > linked to completely. > > This explains my problem (why, whenever I delete an entry from an array, > it also deletes it from every copy of the array). > > So, how could I simply remove an object from an array, without deleting > the object itself? Something like, array_name.remove_at(x) (except > obviously that doesn't exist). > > I've been through the API and can't find anything that seems to fit. I > tried array_name[x] = nil, but that just left an empty entry and didn't > change the length of the array. Even that seems to change the original > object to nil too, as following array_name[x] = nil with > array.delete_at(x) removes the equivalent entry from the original array > as well. > > How can I remove an entry from an array without deleting the object that > the entry refers to? Removing an entry from an array never destroys the object. s = "string" a = [s] a.clear p a # [] p s # "string" As long as a reference to the object exists, the object will still be available. Objects don't even know whether or not they are in collections. David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!