# Problem with copying array

**URL:** <https://www.ruby-forum.com/t/problem-with-copying-array/124090>\
**Category:** Ruby\
**Created:** [December 24, 2007, 4:20pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090 "2007-12-24T16:20:27Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 24, 2007, 4:20pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/1 "2007-12-24T16:20:27Z")

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

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:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 24, 2007, 4:50pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/2 "2007-12-24T16:50:57Z")

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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 24, 2007, 5:05pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/3 "2007-12-24T17:05:35Z")

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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 24, 2007, 5:17pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/4 "2007-12-24T17:17:18Z")

</div>

On 24 Dec 2007, at 16:05, [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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…

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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 24, 2007, 5:22pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/5 "2007-12-24T17:22:33Z")

</div>

[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > > copy = times.dup  
> > > 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.

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 24, 2007, 8:35pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/6 "2007-12-24T20:35:05Z")

</div>

On Dec 24, 2007, at 07:19 , [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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:

`ri Enumerable#map`

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 25, 2007, 1:50pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/7 "2007-12-25T13:50:28Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 25, 2007, 3:35pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/8 "2007-12-25T15:35:13Z")

</div>

On Monday 24 December 2007 16:19:59 [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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:

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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [December 25, 2007, 1:52pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/9 "2007-12-25T13:52:48Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [October 30, 2008, 6:56pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/10 "2008-10-30T18:56:50Z")

</div>

Hi –

On Fri, 31 Oct 2008, Alan Slater wrote:

> it also deletes it from every copy of the 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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [October 30, 2008, 6:47pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/11 "2008-10-30T18:47:58Z")

</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?

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [October 30, 2008, 9:57pm UTC](https://www.ruby-forum.com/t/problem-with-copying-array/124090/12 "2008-10-30T21:57:06Z")

</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:

a -----\> [. , .]  
| |  
v v  
[1,2,3] [4,5,6]  
^ ^  
| |  
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.
