Both dup and clone return different objects, but changing them changes the original object

I have an array of values ​​that I use as a reference for the order when I print the hash values. I would like to change the array so that the array values ​​are “more beautiful”. I decided that I would simply duplicate or clone the array by changing the values ​​and the original object would remain unaffected. However (in irb) ...

@arr = ['stuff', 'things'] a = @arr.clone b = @arr.dup 

So at least a and @arr are different objects:

 a.object_id == @arr.object_id => false 

But now it's weird

 a[0].capitalize! a => ['Stuff', 'things'] @arr => ['Stuff', 'things'] ##<-what? b => ['Stuff', 'things']## <-what??? 

ok ... so changing one changes the rest, lets change it back?

 a[0] = 'stuff' a => ['stuff', 'things'] @arr => ['Stuff', 'things'] ## <- WHAT????? 

For completeness, b [1] .capitalize! has the same effect, capitalizing all three positions of the second level

So ... does the strike at the end of capitalization make it more powerful? Enough to move to other objects? I know other ways to do this, but it seemed extremely strange to me. I guess this has something to do with being a “shallow copy”. Suggestions on the best way to do this?

+7
source share
1 answer

dup and clone create new instances of arrays, but not content, this is not a deep copy.

Cm:

 array0 = ['stuff', 'things'] array1 = array0.clone array2 = array0.dup puts "Array-Ids" p array0.object_id p array1.object_id p array2.object_id puts "Object ids" array0.each_with_index{|_,i| p array0[i].object_id p array1[i].object_id p array2[i].object_id p '--------' } 

Elements inside the array have the same object_id object - this is the same object. Arrays have different object identifiers.

When you a[0].capitalize! you modify an object that is part of three different arrays.

see also

+8
source

All Articles