From: gwtmp01@... Date: 2007-01-25T04:27:08+09:00 Subject: Re: Can Ruby do the Objective-C/Cocoa style alloc/init pattern? On Jan 24, 2007, at 2:07 PM, Eric Hodel wrote: > On Jan 24, 2007, at 01:50, Greg Hurrell wrote: >> The "Class" is sent an "alloc" message (memory is allocated and a new >> instance is actually created) and then the new instance is sent an >> "init" message (allowing the object to prepare itself for use). > > new is written like: > > class Object > def self.new(*args, &block) > obj = allocate > obj.send(:initialize, *args, &block) # initialize is private > obj > end > end A less drastic approach than overriding new in the class is to simply write your own specialized constructor, which can itself call new, allocate, or #initialize, in whatever combination is needed. class A def self.my_constructor(*a, &b) # whatever but good idea to ensure that # an instance of A is returned. end end a = A.my_constructor I think that overriding A#new in such a way that it returns something other than an instance of A should be avoided. The general principle is that a class should be a factory for its own instances. If you want a more general factory pattern, I'd use a module method that delegated construction to an appropriate class: class A;end class B;end module Factory def self.build(a) case a when 'A' then A.new when 'B' then B.new else raise ArgumentError, "'A' or 'B' expected" end end end Factory.build 'A' # instance of A Factory.build 'B' # instance of B Factory.build 'C' # ArgumentError Gary Wright