# Problem with copying array

**URL:** <https://rubytalk.org/t/problem-with-copying-array/43259>\
**Category:** ruby-talk\
**Created:** [24 December 2007 15:19 UTC](https://rubytalk.org/t/problem-with-copying-array/43259 "2007-12-24T15:19:59Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jbieger](https://avatars.discourse-cdn.com/v4/letter/j/a6a055/32.png) [@Jbieger](https://rubytalk.org/u/Jbieger)\
**Post date:** [24 December 2007 15:19 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/1 "2007-12-24T15:19:59Z")

</div>

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  
&nbsp;&nbsp;copy = times.dup  
&nbsp;&nbsp;copy.each do |map|  
&nbsp;&nbsp;&nbsp;&nbsp;map.each do |task|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;task.replace(best\_n(task, 2))  
&nbsp;&nbsp;&nbsp;&nbsp;end  
&nbsp;&nbsp;end  
&nbsp;&nbsp;return copy  
end

Any help would be greatly appreciated!

Jordi

---

<div class="post-metadata">

**Author:** ![Bryan\_Duxbury1](https://avatars.discourse-cdn.com/v4/letter/b/c2a13f/32.png) [@Bryan\_Duxbury1](https://rubytalk.org/u/Bryan_Duxbury1)\
**Post date:** [24 December 2007 15:50 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/2 "2007-12-24T15:50:06Z")

</div>

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, jbieger@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  
> > &nbsp;&nbsp;copy = times.dup  
> > &nbsp;&nbsp;copy.each do |map|  
> > &nbsp;&nbsp;&nbsp;&nbsp;map.each do |task|  
> > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;task.replace(best\_n(task, 2))  
> > &nbsp;&nbsp;&nbsp;&nbsp;end  
> > &nbsp;&nbsp;end  
> > &nbsp;&nbsp;return copy  
> > end
> > 
> > Any help would be greatly appreciated!
> > 
> > Jordi

---

<div class="post-metadata">

**Author:** ![Ryan\_Davis1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/ryan_davis1/32/1848_2.png) [@Ryan\_Davis1](https://rubytalk.org/u/Ryan_Davis1)\
**Post date:** [24 December 2007 19:34 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/3 "2007-12-24T19:34:10Z")

</div>

`ri Enumerable#map`

> **···**
>
> On Dec 24, 2007, at 07:19 , jbieger@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:

---

<div class="post-metadata">

**Author:** ![Jan\_Dvorak](https://avatars.discourse-cdn.com/v4/letter/j/58956e/32.png) [@Jan\_Dvorak](https://rubytalk.org/u/Jan_Dvorak)\
**Post date:** [25 December 2007 14:34 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/4 "2007-12-25T14:34:09Z")

</div>

Another possibility is serialization - it's still your job to make your  
classes serializable and there is stuff that cannot be serialized, but for  
simple cases (multi-dimensional arrays) it works out-of-box:

irb(main):001:0\> a = [["a","b"],[1,2]]  
=\> [["a", "b"], [1, 2]]  
irb(main):002:0\> b = Marshal.load(Marshal.dump(a))  
=\> [["a", "b"], [1, 2]]  
irb(main):003:0\> b[0][0], b[1][0] = "x", 9  
=\> ["x", 9]  
irb(main):004:0\> a  
=\> [["a", "b"], [1, 2]]  
irb(main):005:0\> b  
=\> [["x", "b"], [9, 2]]

Jan

> **···**
>
> On Monday 24 December 2007 16:19:59 jbieger@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:

---

<div class="post-metadata">

**Author:** ![Jbieger](https://avatars.discourse-cdn.com/v4/letter/j/a6a055/32.png) [@Jbieger](https://rubytalk.org/u/Jbieger)\
**Post date:** [24 December 2007 16:05 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/5 "2007-12-24T16:05:00Z")

</div>

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 \<br...@rapleaf.com\> 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

---

<div class="post-metadata">

**Author:** ![Sebastian\_Hungereck1](https://avatars.discourse-cdn.com/v4/letter/s/3ab097/32.png) [@Sebastian\_Hungereck1](https://rubytalk.org/u/Sebastian_Hungereck1)\
**Post date:** [25 December 2007 12:52 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/6 "2007-12-25T12:52:02Z")

</div>

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.

a) There are no primitives in ruby. Everything is an object.  
b) Array#dup never makes a deep copy. You'll always get a different array of  
the same items no matter what the class of these items is.

HTH,  
Sebastian

> **···**
>
> --  
> Jabber: sepp2k@jabber.org  
> ICQ: 205544826

---

<div class="post-metadata">

**Author:** ![Alan\_Slater](https://avatars.discourse-cdn.com/v4/letter/a/c37758/32.png) [@Alan\_Slater](https://rubytalk.org/u/Alan_Slater)\
**Post date:** [30 October 2008 17:47 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/7 "2008-10-30T17:47:06Z")

</div>

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?

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Frederick\_Cheung1](https://avatars.discourse-cdn.com/v4/letter/f/ecc23a/32.png) [@Frederick\_Cheung1](https://rubytalk.org/u/Frederick_Cheung1)\
**Post date:** [24 December 2007 16:16 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/8 "2007-12-24T16:16:15Z")

</div>

> 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...

You need to do it yourself. It may be pretty common, but the exact specifics of how deep to go etc... tend to be rather application dependant.

Fred

> **···**
>
> On 24 Dec 2007, at 16:05, jbieger@gmail.com wrote:
> 
> > Jordi
> > 
> > On 24 dec, 16:50, Bryan Duxbury \<br...@rapleaf.com\> 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  
> > > > &nbsp;&nbsp;copy = times.dup  
> > > > &nbsp;&nbsp;copy.each do |map|  
> > > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;map.each do |task|  
> > > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;task.replace(best\_n(task, 2))  
> > > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
> > > > &nbsp;&nbsp;end  
> > > > &nbsp;&nbsp;return copy  
> > > > end
> > > 
> > > > Any help would be greatly appreciated!
> > > 
> > > > Jordi

---

<div class="post-metadata">

**Author:** ![Matthew\_Harris](https://avatars.discourse-cdn.com/v4/letter/m/51bf81/32.png) [@Matthew\_Harris](https://rubytalk.org/u/Matthew_Harris)\
**Post date:** [24 December 2007 16:21 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/9 "2007-12-24T16:21:57Z")

</div>

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
> 
> > 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
> > 
> > > 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:  
> > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;def prune\_times (times)  
> > > # copy = times  
> > > # copy = Array.new(times)  
> > > # copy = times.clone  
> > > &nbsp;&nbsp;&nbsp;copy = times.dup  
> > > &nbsp;&nbsp;&nbsp;copy.each do |map|  
> > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;map.each do |task|  
> > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;task.replace(best\_n(task, 2))  
> > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end  
> > > &nbsp;&nbsp;&nbsp;end  
> > > &nbsp;&nbsp;&nbsp;return copy  
> > > end  
> > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Any help would be greatly appreciated!  
> > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Jordi  
> > > &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

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.

> **···**
>
> > On 24 dec, 16:50, Bryan Duxbury \<br...@rapleaf.com\> wrote:
> > 
> > > On Dec 24, 2007, at 7:19 AM, jbie...@gmail.com wrote:
> 
> --  
> Matthew Harris
> 
> > **[Inspector General — Matthew D. Harris, Ph.D. CFE](https://matthewharris.org/)**
> >
> > A veteran federal law enforcement officer for nearly two decades, U.S. Special Agent Matthew D. Harris, has become a recognized leader in the federal law enforcement community.

---

<div class="post-metadata">

**Author:** ![David\_A\_Black1](https://avatars.discourse-cdn.com/v4/letter/d/bcef8e/32.png) [@David\_A\_Black1](https://rubytalk.org/u/David_A_Black1)\
**Post date:** [30 October 2008 17:55 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/10 "2008-10-30T17:55:39Z")

</div>

Hi --

> 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 = 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 = 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.

&nbsp;&nbsp;&nbsp;s = "string"  
&nbsp;&nbsp;&nbsp;a = [s]  
&nbsp;&nbsp;&nbsp;a.clear  
&nbsp;&nbsp;&nbsp;p a #   
&nbsp;&nbsp;&nbsp;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

> **···**
>
> On Fri, 31 Oct 2008, Alan Slater wrote:
> 
> --  
> Rails training from David A. Black and Ruby Power and Light:  
> &nbsp;&nbsp;&nbsp;Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL  
> &nbsp;&nbsp;&nbsp;Advancing with Rails January 19-22 Fort Lauderdale, FL \*  
> &nbsp;&nbsp;&nbsp;\* Co-taught with Patrick Ewing!  
> See [http://www.rubypal.com](http://www.rubypal.com) for details and updates!

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [30 October 2008 20:56 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/11 "2008-10-30T20:56:13Z")

</div>

Alan Slater wrote:

> arrays (even arrays of 'primitives' like strings) don't actually  
> contain the objects that fill each entry, they instead (effectively)  
> link to those objects.

Yes - they contain references to 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.

No - they delete the references from the array.

The objects themselves are unchanged. If there are other references to  
them elsewhere in the system, they will live on. If the array element  
was the only reference to the object, so that there are no more now,  
then at some point in the future the object will be garbage-collected.

> This explains my problem (why, whenever I delete an entry from an array,  
> it also deletes it from every copy of the array).

No - you are deleting from a single array, but you have multiple  
references to that array from other places, so they all see the same  
changed array.

A good way to probe this is with the 'object\_id' method.

irb(main):001:0\> a = [[1,2,3],[4,5,6]]  
=\> [[1, 2, 3], [4, 5, 6]]  
irb(main):002:0\> a.object\_id  
=\> -605380508  
irb(main):003:0\> a[0].object\_id  
=\> -605380598  
irb(main):004:0\> a[1].object\_id  
=\> -605380608  
irb(main):005:0\> b = a.dup  
=\> [[1, 2, 3], [4, 5, 6]]  
irb(main):006:0\> b.object\_id  
=\> -605417698  
irb(main):007:0\> b[0].object\_id  
=\> -605380598  
irb(main):008:0\> b[1].object\_id  
=\> -605380608

You can see that a and b are different objects, but a[0] and b[0] point  
to the same object (ditto a[1] and b[1]). Diagramatically:

&nbsp;&nbsp;&nbsp;a -----\> [. , .]  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\> \>  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;v v  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[1,2,3] [4,5,6]  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;^ ^  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\> \>  
&nbsp;&nbsp;&nbsp;b -----\> [. , .]

The sub-arrays don't belong to 'a' any more than they belong to 'b'. So  
the consequence is:

irb(main):009:0\> a[0] \<\< 99  
=\> [1, 2, 3, 99]  
irb(main):010:0\> a  
=\> [[1, 2, 3, 99], [4, 5, 6]]  
irb(main):011:0\> b  
=\> [[1, 2, 3, 99], [4, 5, 6]]

However if you make a modification to one of the outer arrays, e.g. by  
adding or removing an element, this is fine:

irb(main):012:0\> a \<\< [7,8,9]  
=\> [[1, 2, 3, 99], [4, 5, 6], [7, 8, 9]]  
irb(main):013:0\> a  
=\> [[1, 2, 3, 99], [4, 5, 6], [7, 8, 9]]  
irb(main):014:0\> b  
=\> [[1, 2, 3, 99], [4, 5, 6]]

> So, how could I simply remove an object from an array, without deleting  
> the object itself?

slice! or delete\_at

Regards,

Brian.

> **···**
>
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).

---

<div class="post-metadata">

**Author:** ![Sebastian\_Hungereck1](https://avatars.discourse-cdn.com/v4/letter/s/3ab097/32.png) [@Sebastian\_Hungereck1](https://rubytalk.org/u/Sebastian_Hungereck1)\
**Post date:** [25 December 2007 12:49 UTC](https://rubytalk.org/t/problem-with-copying-array/43259/12 "2007-12-25T12:49:44Z")

</div>

Matthew Harris wrote:

> Bryan already mentioned this, but for primitives like strings, integers,  
> floats and whatnot, Ruby knows how to copy these objects

Strings can be copied with the dup method, yes. But if you mean to imply that  
that happens automatically when dupping an array of Strings, you are wrong:

> > arr=["chunky", "bacon"]  
> > arr.dup.each {|str| str.tr!("ck","kc")}  
> > arr

=\> ["khuncy", "bakon"]

Integers and Floats can not be copied at all:

> > 5.dup

TypeError: can't dup Fixnum

> > 5.0.dup

TypeError: allocator undefined for Float

> but if you  
> have custom classes or other classes that don't define their own  
> behavior for copying, then Ruby will keep the reference.

If you dup an array you will always get a new array with references to the old  
objects. dup never makes a deep copy.  
Presumably there is no built-in way to make a deep copy because, as mentioned  
above, some objects (like Integers) can't be copied.

I hope this cleared the confusion a bit,  
Sebastian

> **···**
>
> --  
> Jabber: sepp2k@jabber.org  
> ICQ: 205544826
