On 10/16/09, Brian Candler <b.candler / pobox.com> wrote: > Caleb Clausen wrote:0 >> In general, +clone+ and +dup+ may have different >> semantics in descendent classes. While +clone+ is used to duplicate >> an object, including its internal state, +dup+ typically uses the >> class of the descendent object to create the new instance. >> >> Frankly, I've never been real sure what this is supposed to mean > > I *think* what it means is: clone just copies all the instance > variables, whilst dup calls self.class.new(). > > It's quite common for initialize() to have all sorts of side effects, > creating new objects and so on. So you can expect dup to do all this, > whilst you can expect clone to create an identical object with all the > instance variables pointing at the same objects. Object#dup does not call new; I think it's more like: self.class.allocate.initialize_copy(self). See what happens here: irb(main):001:0> class K irb(main):002:1> def initialize irb(main):003:2> p :initialize irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> k=K.new :initialize => #<K:0xb7ce8ee0> irb(main):008:0> k2=k.dup => #<K:0xb7ce0f38> My reading of those 2 sentences I quoted has now changed. Now I believe that all it's saying is that clone copies the singleton class whereas dup reverts the copy to the object's original class. Tho I still don't fully understand what 'internal state' is supposed to mean. Are instance variables not part of the internal state? Yet both dup and clone copy them. >> initialize_copy apparently is used by both dup and clone. You're >> right, that should be defined (overridden?) instead of dup/clone >> themselves. I rarely remember that. > > I'm not sure I agree with that. The *default* implementation of both dup > and clone does this, as it's the only reasonable thing for Object to do > without any knowledge of its subclasses. But I think the spirit of dup > described above is that dup defined in a subclass should initialize it > using its constructor. > > Since I never use clone, it's a moot point for me as to what it should > do in a subclass. I never used to use clone either, til I discovered a case where I needed to copy the singleton class. Now I'm of the opinion that one should default to clone when a copy is needed, and fall back to dup only when clone is unsuitable.