From: Gregory Brown Date: 2007-01-16T15:54:04+09:00 Subject: Re: How to realize method/function overloading in Ruby? On 1/15/07, gwtmp01@mac.com wrote: > > 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 def do_something(a) send("do_something_with_#{a.class.name.downcase}" end