本文介绍了使用其内容克隆数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要制作一个数组的副本,在原地修改副本,而不影响原始副本。此代码失败
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
副本应与对象不同。为什么它只是一个引用?
解决方案
p>
这是方法。
Marshal.load dump(a))
$ b $ p
这是因为你正在克隆数组,所以数组对象是不同的,但它包含的元素是相同的实例。你可以,例如,也可以做 a.each {| e | b<< e.dup}
为您的情况
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?
解决方案
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
这篇关于使用其内容克隆数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!