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?
The Array. Copy() method in C# is used to copy section of one array to another array. Array. Copy(src, dest, length);
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.
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.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With