Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning an array with its content

I want to make a copy of an array, to modify the copy in-place, without affecting the original one. This code fails

a = [
  '462664',
  '669722',
  '297288',
  '796928',
  '584497',
  '357431'
]
b = a.clone
b.object_id == a.object_id # => false
a[1][2] = 'X'
a[1] #66X722
b[1] #66X722

The copy should be different than the object. Why does it act like if it were just a reference?

like image 539
Redouane Red Avatar asked Jul 16 '15 13:07

Redouane Red


People also ask

How do I copy part of an array to another array?

The Array. Copy() method in C# is used to copy section of one array to another array. Array. Copy(src, dest, length);

What is cloning an array?

The references in the new Array point to the same objects that the references in the original Array point to. In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements. The clone is of the same Type as the original Array.


4 Answers

Instead of calling clone on the array itself, you can call it on each of the array's elements using map:

b = a.map(&:clone)

This works in the example stated in the question, because you get a new instance for each element in the array.

like image 164
wjordan Avatar answered Nov 07 '22 22:11

wjordan


You need to do a deep copy of your array.

Here is the way to do it

Marshal.load(Marshal.dump(a))

This is because you are cloning the array but not the elements inside. So the array object is different but the elements it contains are the same instances. You could, for example, also do a.each{|e| b << e.dup} for your case

like image 33
jazzytomato Avatar answered Nov 07 '22 22:11

jazzytomato


You can use #dup which creates a shallow copy of the object, meaning "the instance variables of object are copied, but not the objects they reference." For instance:

a = [1, 2, 3]

b = a.dup

b # => [1, 2, 3]

Source: https://ruby-doc.org/core-2.5.3/Object.html#method-i-dup

Edit: Listen to Paul below me. I misunderstood the question.

like image 23
Zachary White Avatar answered Nov 07 '22 20:11

Zachary White


Try this:

b = [] #create a new array 
b.replace(a) #replace the content of array b with the content from array a

At this point, these two arrays are references to different objects and content are the same.

like image 20
Maya Novarini Avatar answered Nov 07 '22 22:11

Maya Novarini