克隆对象的变化值 [英] Change value of a cloned object
问题描述
我有了一个实例变量数组称为对象 my_array
。我通过声明它 attr_accessor中
。
I have an object that has an instance variable array called my_array
. I declare it via attr_accessor
.
my_object.my_array = [1,2,3] # <= I don't know the max size of my_array(it can be dynamic)
我想创建一个 my_object
同一个对象,并填写了 my_array
只有一个元素。该元素内的值从 my_array
的元素的每个值(从 my_object
)。由于大小 my_array
是动态的,我想我需要通过来迭代每它
。
I want to create the same object with my_object
and fill its my_array
with only one element. The value inside that element is each value from my_array
's element (from my_object
). Because the size of my_array
is dynamic I suppose I need to iterate it via each
.
下面是我的尝试:
my_object.my_array.each do |element| # <= my_object is a special object
new_object = nil unless new_object.nil?
new_object = my_object.clone # <= I create new object with same class with my_object
new_object.my_array.clear # <= clear all element inside it.
new_object.my_array.push(element) # assign element value to the first element.
# rest of code #
new_object = nil
end
迭代未正确迭代。 my_object.my_array
的大小为3,那么它应该迭代三次,但它不是,它只是迭代一次。我相信这是因为 new_object.my_array.clear
,但我克隆它从 my_object
,那么为什么会这样?
The iteration is not iterating properly. The size of my_object.my_array
is 3, then it should iterating three times, but it's not, it's only iterating one time. I believe it's because of new_object.my_array.clear
, but I cloned it from my_object
, so why this happened?
推荐答案
的问题是,克隆
将一个浅克隆,而不是一个深克隆。换句话说, my_array
是一个参考和克隆的实例引用相同的数组在内存中。试想一下:
The problem is, that clone
will make a shallow clone, not a deep clone. In other words, my_array
is a reference and the cloned instance references the same array in memory. Consider:
class MyClass
attr_accessor :my_array
end
a = MyClass.new
a.my_array = [1, 2, 3]
a.my_array
#=> [1, 2, 3]
b = a.clone
b.my_array.push(4)
b.my_array
#=> [1, 2, 3, 4]
a.my_array # also changed!
#=> [1, 2, 3, 4]
为了解决这个问题,你需要扩展 initialize_copy
方法也克隆数组:
In order to fix this, you need to extend the initialize_copy
method to also clone the array:
class MyClass
attr_accessor :my_array
def initialize_copy(orig)
super
self.my_array = orig.my_array.clone
end
end
a = MyClass.new
a.my_array = [1, 2, 3]
a.my_array
#=> [1, 2, 3]
b = a.clone
b.my_array.push(4)
b.my_array
#=> [1, 2, 3, 4]
a.my_array # did not change, works as expected
#=> [1, 2, 3]
这篇关于克隆对象的变化值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!