我有一个类,其成员之一是数组。我需要相当多地复制这个类的对象。我发现如果我复制对象,即使使用clone
,数组成员仍然引用相同的数组:
class MyClass
def initialize(a, b, items)
@a = a
@b = b
@items = items
end
attr_accessor :a, :b, :items
end
=> nil
2.1.5 :009 > test = MyClass.new(2, 3, [1, 2, 3])
=> #<MyClass:0x0000000231e7f8 @a=2, @b=3, @items=[1, 2, 3]>
2.1.5 :010 > newtest = test.clone
=> #<MyClass:0x00000002312368 @a=2, @b=3, @items=[1, 2, 3]>
2.1.5 :011 > newtest.a = 55
=> 55
2.1.5 :012 > newtest
=> #<MyClass:0x00000002312368 @a=55, @b=3, @items=[1, 2, 3]>
2.1.5 :013 > test
=> #<MyClass:0x0000000231e7f8 @a=2, @b=3, @items=[1, 2, 3]>
2.1.5 :014 > newtest.items[1] = nil
=> nil
2.1.5 :015 > newtest
=> #<MyClass:0x00000002312368 @a=55, @b=3, @items=[1, nil, 3]>
2.1.5 :016 > test
=> #<MyClass:0x0000000231e7f8 @a=2, @b=3, @items=[1, nil, 3]>
如何使用对象复制数组?
答案 0 :(得分:2)
答案 1 :(得分:1)
我们有一个本机实现来执行ruby对象的深层克隆:ruby_deep_clone
使用gem安装它:
gem install ruby_deep_clone
使用示例:
require "deep_clone"
object = SomeComplexClass.new()
cloned_object = DeepClone.clone(object)