From: Pit Capitain Date: 2007-01-07T02:43:06+09:00 Subject: Re: cloning object with array members Shea, you found your answer in the meantime, but I wanted to show you what was wrong with your other attempts: >> a = MyClass.new >> b = a.clone >> >> This method leaves 'b.arr1' pointing to the same data as a.arr1. Yes, the default #dup and #clone create a shallow copy. >> def clone >> rslt = super.clone >> end >> >> This blows the stack, I believe because all methods are inherited >> virtually. "super" isn't the same as in Java. super calls the same method of the superclass, so what you are doing here is: temp = super rslt = temp.clone Since temp is an instance of MyClass, you're calling clone again, which gives you and endless recursion. The correct way would have been: def clone super end But this obviously doen't help you. >> 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. The solution to this problem was: >> 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. And here, as you've noted yourself, you just forgot to return your new instance. Regards, Pit