I've never extensively used any language that has this feature, but
it's always struck me as a bit strange, and very brittle. What if you
want two method behaviors, but both behaviors involve having the same
number of arguments? It's always seemed to me a bit like having
methods dispatch on what letter of the alphabet their parameters begin
with.
So... I guess my view is that Ruby has evolved beyond it, though there
may be some use for it that I'm just not seeing.
Actually, I would say that Ruby uses overloading far more than most
other languages. What does "overloading" actually mean? Basically it
means implementing more than one behaviour for the same language
element. You do that in Ruby perhaps even more than in most other
languages. In Ruby you even do it at run-time by extending classes,
replacing functions, etc.
Consider the top-level method "open". If you mixin the functionality
from the open-uri library, you are basically overloading that function
to behave differently according to the value of its arguments. Or
perhaps a better example is the 'puts' function. I don't know if it is
written in Ruby, but an implementation might look something like this:
def puts(arg)
if arg.is_a? String then
# write out the string
elsif arg.is_a? Number
s = arg.to_s
# write out the string s
else
# etc. etc.
end
end
This is basically overloading of a method. But it is implemented
entirely by the programmer with no help from the language. Now, in a
statically typed language such as Java, you cannot do the above because
the argument must specify a type. Thus, you have to do something like
void puts(String arg) {
# write out the string
}
void puts(int arg) {
# convert the int to a string and write it out
}
(Ignoring for a moment the fact that Java 1.5 introduced auto-boxing of
primitive types.)
Which is better? Which uses overloading more than the other? Neither of
them. But a language with static typing is often somewhat limited in
how much they can overload a function.
Getting back to the OP's question. What I believe he simply wants, is
some language construct that would assist him when overloading method
behaviour depending on the number of actual arguments received. That a
fair request in itself. Unfortunately, as others have pointed out, it
doesn't go too well with the fact that defining a method more than once
means overwriting the old definitions. However, I am sure some
meta-programming expert could come up with a function that would allow
us to write something like this:
overload do
def methodName(arg)
# code block A
end
def methodName(arg1, arg2)
# code block B
end
end
Basically this would be translated into something like:
def methodName1(arg)
# code block A
end
def methodName2(arg1, arg2)
# code block B
end
def methodName(arg1, arg2=nil)
if arg2.nil? then
methodName1(arg1)
else
methodName2(arg1, arg2)
end
end
I think that might be very useful in some cases actually. I wonder if
it can be done.