Tim Hunter
12/4/2006 3:25:00 AM
Daniel Finnie wrote:
> In Java, you could write the following code:
> public void foo(int x)
> { /* do something*/ }
>
> public void foo(String x)
> { /* do something*/ }
>
> int x1
> String x2
>
> foo(x1)
> foo(x2)
>
> The 2nd to last line would call the first foo and the last line would
> call the 2nd foo.
>
> Is there a way to do this in Ruby? I am aware of method(*args) and
> case...when but I think Java's version is cleaner and more readable.
> I also know that variables in Ruby are dynamically typed, the method
> that is called should be based on the most recent type of the variable
> being passed.
>
> I don't want to do this:
> def foo(arg)
> if arg.type_of? String
> # do something
> elsif arg.type_of? Numeric
> #do something
> else
> raise args error
> end
> end
>
> thanks,
> Dan
>
Java's (and C++'s) kind of method overloading just isn't do-able in
Ruby. Generally, if you have a method that can take either a String or a
Numeric argument, then you create two methods, one that takes a String
argument and another for the Numeric argument.
Switching on the class of an argument is also regarded with suspicion
but is acceptable in some cases. Search for "duck typing" in the Pickaxe
or in the archives of this mailing list for exhaustive discussions.