From: gwtmp01@... Date: 2007-01-16T00:07:31+09:00 Subject: Re: How to realize method/function overloading in Ruby? On Jan 15, 2007, at 6:38 AM, Shiwei Zhang wrote: > 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? This is a common question. The short answer is that function overloading is based on knowing the static types of the actual arguments to a method and in Ruby the entire notion of 'static types of the actual arguments' is pretty much non-existent. The longer answer is that for Ruby to provide some sort of overloading a new syntax for method definition would be required and then the method lookup algorithm would have to be updated. Warning: pseudo code ahead. def do_something( a as Array) #... end def do_something( a as Hash) #... end def do_something(a) #... end do_something([1,2]) # as Array version do_something({1,2}) # as Hash version do_something(1) # unspecified version This would really complicate the method dispatch mechanism as the class of every argument would have to be examined *each* time any method is called. I used literal arrays, hashes, and integers in the example but in general they would just be arbitrary expressions. In any case some sort of algorithm would have to be run each time a method was called. This would drastically increase method call overhead in Ruby. This is a lot of work when the programmer can achieve the same goal with the existing language quite concisely: def do_something(a) case a when Array # work with array when Hash # work with hash else # assume integer end end Same effect, no language changes, and the algorithm is explicit and flexible rather than implicit and rigid. There is yet another approach. Define different methods for different arguments: def do_something_with_array(a) # assume a is an array end def do_something_with_hash(h) # assume h is a hash end def do_something_with_int(i) # assume i is an int end do_something_with_array([1,2]) do_something_with_hash({1,2}) do_something_with_int(3) This is of course doing by hand what static overloading does 'automatically'. In Ruby you still end up doing regular method lookup for do_something_with_array and company. The bottom line is that Ruby already provides several methods to deal with complex argument lists. Adding some sort of class declarations to formal arguments goes against the grain of Ruby's design with little if any benefit to outweigh the added complexity. P.S. I seem to remember that there was a considerable amount of criticism in the C++ community about static function overloading vs. dynamic dispatch. I'm not sure what the situation is today. Gary Wright