Both dup and clone return different objects, but modifying them alters the original object

六月ゝ 毕业季﹏ 提交于 2019-12-22 04:46:11

问题


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:


dupand 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!