From: Avdi Grimm Date: 2007-03-20T23:09:31+09:00 Subject: Re: does Ruby not support multiple "initialize" methods for a class??? ------=_Part_127719_20274694.1174399768889 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 3/20/07, Stefano Crocco wrote: > > You could just declare an initialize method which takes any number of > arguments, then detect the scenario according to the passed argument. For > example, assuming that in one case the first argument is a number and in > the > second is a string, you could do: > > class MyClass > > def initialize(*args) > if args[0].is_a? Numeric > #perform initialization in first case > elsif args[0].is_a? String > #perform initialization in second case > else raise TypeError > end > end This looks a lot nicer using "case": class MyClass def initialize(*args) case args0 when Numeric # ...perform numeric initialization when String # ...perform string initialization else raise TypeError end end end Of course, you can get a lot fancier with your "case" statement using regular expressions, ranges, multiple matchers per case, etc. The sky's the limit... -- Avdi ------=_Part_127719_20274694.1174399768889--