dup和clone都返回不同的对象,但修改它们会改变原始对象 [英] Both dup and clone return different objects, but modifying them alters the original object

查看:157
本文介绍了dup和clone都返回不同的对象,但修改它们会改变原始对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个值数组,当我打印哈希值时,我用作订单的引用。我想修改数组,使数组值漂亮。我想我只是复制或克隆数组,更改值,原始对象将保持未被加载。但是(在irb)...

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

所以,至少,a和@arr是不同的对象:

So, at the very least, a and @arr are different objects:

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

但现在变得奇怪了

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

ok ...所以修改一个改变别人,让它改回来?

ok... so modifying one changes the others, lets change it back?

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

为了完整性b [1] .capitalize!具有相同的效果,利用所有三个阵列的第二个位置

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?

推荐答案

dup code>克隆创建数组的新实例,但不是内容,它不是深层次的副本。

dupand clone make new instances of the arrays, but not of the content, it is no deep copy.

请参阅: / p>

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 '--------'
}

数组中的元素共享相同的object_id - 它们是相同的对象。数组有不同的对象ids。

The elements inside the array share the same object_id - they are the same object. The arrays have different object ids.

当你 a [0] .capitalize!你修改一个对象,

When you a[0].capitalize! you modify an object, which is part in three different arrays.

另请参见

  • Duplicating a Ruby array of strings
  • Deep copy of arrays in Ruby
  • How to create a deep copy of an object in Ruby?

这篇关于dup和clone都返回不同的对象,但修改它们会改变原始对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆