"Dave Burt" <burtdav / hotmail.com> schrieb im Newsbeitrag
news:Ew3qc.43766$TT.3729 / news-server.bigpond.net.au...
> <imodev / softhome.net> wrote...
> > ... what about overloading based on parameter's
> > classes? Something like (in C++):
> >
> > int test(int a)
> > int test(char* a)
> >
> > Is there any way or must I write some code like: if (a.class ==
'class')
> > then...?
>
> Yes. The class method returns a Class object. So you can compare:
>     a.class <= Integer
> to check if a is an Integer or any subclass of Integer.
>
> Better, you can use the kind_of? method:
>     a.kind_of?(Integer)
> which is more obvious.

And then there is the third idiom:

Integer === a

which btw nicely integrates in case statements as you show below:

> But for this situation, a case statement is probably best:
>
> def test(a)
>   case a
>     when Integer
>       # ...
>     when String
>       # ...
>     else
>       raise ArgumentError, "test(a): parameter must be Integer or
String",
> caller
>   end
> end

Btw: there's a gotcha with the idiom on the wiki:

def fred(*args)
  case args.collect { |a| a.type}
    when [Float, Fixnum, String]
      f, i, s = args
      # ...


This will not use Class#=== i.e. match only if the arguments' types match
identical (instead of sub classes matching with superclasses for all the
three idioms listed above).

Kind regards

    robert