From: Trans Date: 2008-01-23T07:14:55+09:00 Subject: Re: Bugs in Facets Cloneable? On Jan 22, 11:09 am, Ken Bloom wrote: > I was just looking at the Cloneable module from the Facets' library, > because it's useful, and noticed a couple of possible bugs. Is my > assessment of this correct? > > module Cloneable > def clone > sibling = self.class.new > instance_variables.each do |ivar| > value = self.instance_variable_get(ivar) > sibling.instance_variable_set(ivar, value.dup) #rake_dup) > end > sibling > end > alias_method :dup, :clone > end > > Question 1: Shouldn't #clone use self.class.allocate instead of > self.class.new? Better yet, shouldn't the superclass's dup be called > somehow? > > Question 2: Shouldn't #clone and #dup be implemented differently, so that > #clone can freeze the newly created object? Hmmm.. some good questions. This bit of code came from Rake a long time ago. I never really analysed it, and just accepted it at face value. I suspect the thing to do these days is to use #allocate and #initialize_copy instead. I point out, if anyone is wondering, the difference between this and the built-in clone/dup is that the above dups the instance vars. The difference between the two being that #dup carries over the tainted state while #clone carries over the tainted and frozen states (correct?). Since we are duplicating the instance vars here, there is no reason to consider taintedness. But frozen should still apply (yes?). Could anyone else with a bit more assuredness about Ruby's behavior confirm this or offer the proper perspective if it is wrong? Thanks, T.