Why doesn’t ruby support method overloading?

“Overloading” is a term that simply doesn’t even make sense in Ruby. It is basically a synonym for “static argument-based dispatch”, but Ruby doesn’t have static dispatch at all. So, the reason why Ruby doesn’t support static dispatch based on the arguments, is because it doesn’t support static dispatch, period. It doesn’t support static dispatch of any kind, whether argument-based or otherwise.

Now, if you are not actually specifically asking about overloading, but maybe about dynamic argument-based dispatch, then the answer is: because Matz didn’t implement it. Because nobody else bothered to propose it. Because nobody else bothered to implement it.

In general, dynamic argument-based dispatch in a language with optional arguments and variable-length argument lists, is very hard to get right, and even harder to keep it understandable. Even in languages with static argument-based dispatch and without optional arguments (like Java, for example), it is sometimes almost impossible to tell for a mere mortal, which overload is going to be picked.

In C#, you can actually encode any 3-SAT problem into overload resolution, which means that overload resolution in C# is NP-hard.

Now try that with dynamic dispatch, where you have the additional time dimension to keep in your head.

There are languages which dynamically dispatch based on all arguments of a procedure, as opposed to object-oriented languages, which only dispatch on the “hidden” zeroth self argument. Common Lisp, for example, dispatches on the dynamic types and even the dynamic values of all arguments. Clojure dispatches on an arbitrary function of all arguments (which BTW is extremely cool and extremely powerful).

But I don’t know of any OO language with dynamic argument-based dispatch. Martin Odersky said that he might consider adding argument-based dispatch to Scala, but only if he can remove overloading at the same time and be backwards-compatible both with existing Scala code that uses overloading and compatible with Java (he especially mentioned Swing and AWT which play some extremely complex tricks exercising pretty much every nasty dark corner case of Java’s rather complex overloading rules). I’ve had some ideas myself about adding argument-based dispatch to Ruby, but I never could figure out how to do it in a backwards-compatible manner.

Leave a Comment