From: Vincent Fourmond Date: 2007-01-12T18:22:49+09:00 Subject: Re: Why doesn't Ruby allow for overloaded methods within a class Wes Gamble wrote: > (from a Java refugee) > > All, > > I've done quite a bit of googling and read a bunch of posts about this, > but I'm looking for a simple explanation of why Ruby doesn't support > method overloading within a class to allow methods with the same name > but different numbers of arguments. I understand that you can't do > method overloading with the same # of arguments since you don't know any > "types" of input parameters when you invoke a method. > > But...it seems like you could allow it for different numbers of input > parameters. > > Here's an example of what I mean: > class Foo > def methname(x,y) > ... > end > > def methname(x, y, z) > ... > end > end > > I'm comfortable with how to implement this using a method with varargs > and appropriate logic, and I'm aware of arguments that the methods > should probably be different in name if their set of input parameters > are of different size. > > But it seems like this kind method overloading would be doable in Ruby. > Is it possible? > Is it not available because there's a feeling that it isn't needed? Use default arguments def methname(x,y, z = false) if z else end If false is a valid value for z, you can try z = :special if z == :special Moreover, most of the time, quite a bit of code is shared from the 2-args version to the 3-args version. Actually, if that is not the case, it is probably a sign that the functionality shouldn't be regrouped under a unique name. Cheers, Vince -- Vincent Fourmond, PhD student http://vincent.fourmond.neuf.fr/