I want to use overloading feature in Ruby like many other languages, but Ruby itself does not support this feature.
Do I have to implement it using the way that define a method with *args argument and determine the number and types of the arguments inside the method? Some like:
class A
def foo(*args)
case (args.length)
when 1
do something
when 2
do something-else
....
end
end
end
You can see, it is really ugly than directly overloading.
I want to know whether there is any keywords or some other manners (like a meta-programming module) that could allow me to define an overloading method in a more elegant way.
You could try some meta programming to reach your target.
See the following code:
You can define your overloaded method with
define_overload_method. Parameters are the method name and a list of procedures. The methodmethodnameis created and calls the corresponding method. Which method is determined by the number of parameters (Not type!).An alternative syntax would be:
def_overloaddefines the frame for your overloaded methods,overload_methoddefines one ‘overload-method’.But as already mentioned by Holger:
I was curious how I could implement a version with type sensitive overloading. Here it is:
When you call it with
You get