From: Timothy Hunter Date: 2005-12-06T11:17:34+09:00 Subject: Re: Overloaded constructors in Ruby Kyle Heon wrote: > 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 > end Actually, defining default values for arguments is a very "Ruby" way of handling this case. If the arguments have sensible default values, then I'd argue that it's the best solution. You could also use a hash to simulate named parameters if that's what floats your boat. Another very "Ruby" thing to do is to define multiple constructors with different names. Something I've done is to define a "basic" constructor and then define one or more methods that modify the basic instance. For example, suppose you have two kinds of rectangles, a regular square-cornered rectangle and a rectangle with rounded corners. The difference between the two rectangles is that the rounded rectangle needs an extra 2 numbers to define the radii of the ovals that make up the corner. If you want a plain rectangle just call "new". If you want a rounded rectangle, modify the newly-constructed instance by calling "rounded" on it. class Rectangle def initialize(width, height) @width, @height = width, height end def rounded(rx, ry) @rx, @ry = rx, ry end end rect = Rectangle.new(20, 30) round_rect = Rectangle.new(20, 30).rounded(2, 3)