From: ptkwt@... (Phil Tomson) Date: 2005-12-06T16:27:33+09:00 Subject: Re: Overloaded constructors in Ruby In article <20051206012149.EF632339CD@beryllium.ruby-lang.org>, Kyle Heon wrote: >I have a class that I want to have a number of overloaded constructors for. > >I tried doing something like this: > >class GravPoint > def initialize() > this(0, 0, 0, 0, 0) > end > > def initialize(x, y, strength) > this(x, y, strength, 0, 0) > end > > def initialize(x, y, strength, ctime, life) > @x, @y, @strength, @ctime, @life = x, y, strength, ctime, life > end >end > >When I then run GravPoint.new() I get the following error: > >GravPoint.rb:23:in `initialize': wrong number of arguments (0 for 5) >(ArgumentError) > >I think I understand the error, it's expecting 5 arguments (based on the >last constructor) but I don't the "Ruby" way to set this up. What am I >missing? > >I was able to get this to work, but was hoping that I could do it in a >format closer to the above to make it a little more flexible to use. > >class GravPoint > def initialize(x = 0, y = 0, strength = 0, ctime = 0, life = 0 ) > @x, @y, @strength, @ctime, @life = x, y, strength, ctime, life > end def GravPoint.from_x_y_strength(x,y,strength) new(x,y,strength) end >end gp = GravPoint.new #matches your first constructor gp1= GravPoint.from_x_y_strength 5.5,4.2,254 #matches your 2nd c'tor gp3= GravPoint.new(1,2,3,4,5) #matches your last c'tor Phil