나는 Ruby (MRI 1.9.3)에서 객체를 딥 복사하는 몇 가지 기법을 찾고 있습니다.
다음 예제를 보았지만 #dup
메서드 구현에 대해 확신하지 못했습니다. 테스트를 거쳤지만 제대로 작동하지만 메서드의 논리적 단계를 이해할 수 없으므로 자체 코드에서 사용하기가 쉽지 않습니다.Ruby : 객체 딥 (object deep copy)
@name = @name.dup
은 내부의 iVar 을 참조하고 있습니까? 방법? 나는 그것을 볼 수 없다.
누구나 설명해 주시겠습니까?
또한 더 좋은 방법이 있습니까?
class MyClass
attr_accessor :name
def initialize(arg_str) # called on MyClass.new("string")
@name = arg_str # initialize an instance variable
end
def dup
the_copy = super # shallow copy calling Object.dup
@name = @name.dup # new copy of istance variable
return the_copy # return the copied object
end
end
관련 : http://stackoverflow.com/questions/8206523/how-to-create-a-deep-copy-of-an-object-in-ruby –