From: Robert Klemme Date: 2007-08-20T17:42:35+09:00 Subject: Re: Named Constructor Idiom in Ruby? 2007/8/18, Stefano Crocco : > Alle sabato 18 agosto 2007, Arlen Christian Mart Cuss ha scritto: > > Hi all, > > > > I'm almost certain there's a good way to do this, but I seem to have > > lost hold of the thought of how -- is there a straight-forward/neat way > > to do the named constructor idiom in Ruby? > > > > In C++ terms, a class like this implements it: > > > > class A { > > public: > > static A something() { > > A a; > > // do something special to a > > return a; > > } > > > > static A otherthing() { > > A a; > > // some other special thing to a > > return a; > > } > > > > protected: > > A(); > > }; > > > > The result is that we can't construct A directly, only by one of the two > > 'named' constructors. Is there any way to achieve a similar thing using > > protection in Ruby? > > > > Thanks, > > > > Arlen. > > You need to make the new class method of class A private. Then, you implement > the class methods you want to make public to create the instances of A: > > class A > > private_class_method :new > > def self.special_method_1 > a = A.new > #do something special > a > end > > def self.special_method_2 > a = A.new > #do something else special > a > end > > end > > a1 = A.special_method1 > a2 = A.special_method2 > > I hope this helps A small glitch: irb(main):020:0> a1 = A.special_method_1 NoMethodError: private method `new' called for A:Class from (irb):6:in `special_method_1' from (irb):20 from :0 You need to remove the "A." when calling "new" after making it private. It's not needed anyway. irb(main):021:0> def A.special_method_1 irb(main):022:1> a=new irb(main):023:1> a irb(main):024:1> end => nil irb(main):025:0> a1 = A.special_method_1 => # Kind regards robert