From: Shea Martin Date: 2007-01-06T06:40:12+09:00 Subject: cloning object with array members Consider a simple class like this: class MyClass def initialize @var1 = '' @arr1 = [] end end Now if I have an instance of MyClass, and want to clone it, what is the 'cleanest' way to do this? a = MyClass.new b = a.clone This method leaves 'b.arr1' pointing to the same data as a.arr1. Hmmm... I'll try overriding clone, and manually deal with the arrays: def clone rslt = super.clone end This blows the stack, I believe because all methods are inherited virtually. Ok, so now I have to manually copy everything in clone, whatever, I am getting sick of this: def clone rslt = MyClass.new rslt.var1 = @var1 rslt.arr1 = @arr1.clone rslt end Turns out this does not compute either, as there is no method var1= or arr1= ! I want to keep var1 private, so can't go this route either. One more attempt: def clone rslt = MyClass.new self.instance_variables.each do |member| rslt.instance_variable_set( member, self.instance_variable_get(member).clone ) end end This fails as the methos do not seem to copy over. There has to be a simple way to do something like this? What is common recipe for something like this? Should this really be that hard in ruby? ~S