This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Method overloading in Ruby
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
In a recent blog entry, Guido waxes rhapsodic about method overloading in Python 3000.
Admit it. There are times you want to do this in Ruby. Oh, sure, there are ways around it - default parameters, separate methods, case/type checks - but there are times you just WANT overloading, dammit!
So, how can we do this in Ruby? One way to do this is via Ryan Pavlik's strongtyping package. Here's an example:
So, we've got a 'bar' method that takes either two Strings, or a String and an Integer, executing the appropriate block, or raising an error if a bad type is passed (which is what the overload_default method is for). That syntax isn't great, though. Having the method signatures inside the method itself just looks funny.
Another possibility is Nobu's 'overload' package, which you can find here. Here's an example:
require "overload"
class Foo
def initialize
puts "No args"
end
overload(:initialize)
def initialize(x)
puts "One arg (Fixnum)"
end
overload(:initialize, Fixnum)
def initialize(x)
puts "One arg (String)"
end
overload(:initialize, String)
end
Foo.new # "No args"
Foo.new(1) # "One arg (Fixnum)"
Foo.new('hello') # "One arg (String)"
Prettier syntax, but without some of the features of Ryan's strongtyping package.
In Syndey Evan had (mostly, I think) worked out a strongtyping behavior, so you could do something like this:
require 'strongtypingbehavior'
def bar(String x, String y)
...
end
def bar(String x, Integer y)
...
end
Pretty nice, eh? Sydney, like Ruby, isn't compiled, so it's strictly a bunch of lexer/parser tricks happening there, and slows your code down a bit. I actually wasn't convinced we should have a strongtyping behavior in Sydney, because I didn't want folks coming from static languages to write this kind of code. In my humble opinion using method signatures in dynamic languages should be used sparingly, not as a first resort. It's too easy to write brittle code with this. Use duck typing instead.