From: vincent.fourmond@9online.fr
Date: 2007-01-16T02:34:20+09:00
Subject: Re: How to realize method/function overloading in Ruby?
> I think Function Overloading in C++ is very meaningful. And
> currently
> the case for me is: How I can make use of method/function
> overloading
> in Ruby?
> Besides you might tell me Ruby is designed to exclude method
> overloading, can you tell me sth more for the Overloading purpose?
There are quite a few thread on overloading around here, but I'll make a short summary (once for all, hopefully ?). C++ overloading has basically two purposes:
1) get around strict typing limitations (a function working on numbers might want to work on int, float, double...)
2) provide defalt values (though it is not really overloading, it really looks like it).
In my opinion, any other way to use overloading (that is, a function doing something completely different when called with (int, double) than with (double) is characteristic of bad programming practices).
Ruby provides solutions for both cases:
1) you don't need to declare type for a ruby function, so you can call one unique function with many different types. If you need to separate some cases depending on the type of one of the argument, try something like:
case argument
when String
do something with the string
when Array
...
end
The best approach to this is probably 'duck typing', that is: you don't care what objects the function is fed to, as long as the behave correctly (they have the right methods that do something appropriate)
2) ruby provides default arguments as well (more powerful than C++):
irb(main):004:0> def m(a, b = 0, c = a)
irb(main):005:1> [a,b,c]
irb(main):006:1> end
=> nil
irb(main):007:0> m(1)
=> [1, 0, 1]
irb(main):008:0>
Does that answer your question, or you know some other uses of overloading I didn't mention ?
Cheers,
Vince