From: Dave Thomas Date: 2003-08-13T02:49:52+09:00 Subject: Re: common constructor idioms Scott Thompson wrote: > In C++ one often declares a constructor that accepts another instance of > this class. For those familiar with C++ syntax I'm talking about: > > class MyClass { > /* other interesting stuff in this class deleted */ > > /* Copy constructor */ > MyClass(const MyClass &objectToCopy); > }; > > I guess you could do something similar in Ruby like this: > > class MyClass > def initialize(x) > if x.class == MyClass then > #some code to duplicate stuff in x > else > #potentially other initialization mechanisms here > end > end > end > > > Though there are bound to be differing opinions on the subject (and I > have no desire to start a flame war so please be kind) I was curious to > know is a popular idiom in Ruby code or not? More to the point, would > someone who was using an Ruby extension reasonably assume that this > initialization mechanism was included? Personally I wouldn't overload #new like this. Instead I'd add a new static construction method class Boat def Boat.from_other_boat(b) # ... end end ...or... I'd simply implement an instance method to duplicate a particular object. I wrote a blog entry on constructors: http://pragprog.com/pragdave/Practices/ConstructionMethods.rdoc,v Cheers Dave