From: "Brian Schröder" Date: 2005-02-23T04:59:42+09:00 Subject: Re: Constructor overloading??? On Wed, 23 Feb 2005 02:22:15 +0900, Eliah Hecht wrote: > I've run into this before when (for instance) I want initialize() to > do one thing if it gets one arg, and a totally different thing if it > gets two args. AFAIK, the only way to do this is to bundle the args up > in an array, and to look at the size of that, which just feels clumsy. > > -Eliah. If the initializers are totally different, then it may make sense to create two new differently named constructors. I think that makes the program better readable. Greetings, Brian > > On Tue, 22 Feb 2005 06:31:00 +0900, James G. Britt > wrote: > > On Tue, 22 Feb 2005 06:04:07 +0900, Panagiotis Karvounis > > wrote: > > > Hi, > > > > > > Does Ruby support constructor overloading? > > > > No; Ruby desn't support method overloading. But you can pass a > > variable number of arguments and do some logic based on what's given. > > > > One approach is to define all the args and set default values: > > > > def initialize ( x, y="Hey!", z=nil ) > > end > > > > Another might be to just accept any number of args as an array: > > > > def initialize ( *args) > > # The array args now has the arguments > > end > > > > Or combine them > > > > def initialize (x=0, y="Hey!", *z=nil ) > > end > > > > Or use a hash as the primary argument: > > > > def initialize ( h={} ) > > # Now go look for named arguments in the hash > > end > > > > f = Foo.new( :user_name => "Jimbo!", :country => "Bronx" ) > > > > What are you trying to accomplish? > > > > > > James > > > > > > -- -- Brian Schr�der http://ruby.brian-schroeder.de/