From: Alan Chen Date: 2002-06-07T05:38:20+09:00 Subject: Re: Returning an instance from a different class from new On Fri, Jun 07, 2002 at 04:53:23AM +0900, Jos Backus wrote: > [For some reason I am no longer subscribed to ruby-talk and I don't get any > mail back from the ctl address, which is why I have to use my provider's > crappy newsserver :-(] > > How do I make the following return Bar instead of Foo? > > class Foo > def initialize(sel) > case sel > when "1" > return Bar.new > when "2" > return Baz.new > end > end > end > > class Bar < Foo > def initialize > self > end > end > > class Baz < Foo > def initialize > self > end > end > > o = Foo.new("1") > p o.type > > Thanks, > Jos I would recommend breaking out the functionality in Foo's initialize into a factory function. module FooFactory def build(sel) case sel when "1" return Bar.new when "2" return Baz.new end end class Foo # ... end class Bar < Foo # ... end end o = FooFactory.build('1') p o.type -- Alan Chen Digikata LLC http://digikata.com