克隆数组及其内容 [英] Cloning an array with its content
本文介绍了克隆数组及其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
这篇关于克隆数组及其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文