问题
I have an array of values that I use as a reference for order when I'm printing out hash values. I'd like to modify the array so that the array values are "prettier". I figured I'd just dup or clone the array, change the values and the original object would remain unchanaged. However (in irb)...
@arr = ['stuff', 'things']
a = @arr.clone
b = @arr.dup
So, at the very least, a and @arr are different objects:
a.object_id == @arr.object_id
=> false
But now it gets strange
a[0].capitalize!
a
=> ['Stuff', 'things']
@arr
=> ['Stuff', 'things'] ##<-what?
b
=> ['Stuff', 'things']## <-what???
ok... so modifying one changes the others, 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 array's second position
So... does the bang on the end of capitalize make it extra potent? Enough to cross over to other objects?? I know of other ways of doing this, but this just seemed extremely odd to me. I assume this has something to do with being a "shallow copy". Suggestions on the best way to do this?
回答1:
dup
and clone
make new instances of the arrays, but not of the content, it is no deep copy.
See:
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 '--------'
}
The elements inside the array share the same object_id - they are the same object. The arrays have different object ids.
When you a[0].capitalize!
you modify an object, which is part in three different arrays.
See also
- Duplicating a Ruby array of strings
- Deep copy of arrays in Ruby
- How to create a deep copy of an object in Ruby?
来源:https://stackoverflow.com/questions/12502715/both-dup-and-clone-return-different-objects-but-modifying-them-alters-the-origi