On Aug 6, 2005, at 1:01 PM, Stephan Mueller wrote:

> Hello,
>
> i am kind of a newbi, please forgive me if i am asking stale  
> questions.
>
> I want to adjust the initialization of an object according to the
> parameters given to new.
>
> My first idea was polymorphism I know from languages like java:
>
>  def initialize
>    puts("no param")
>  end
>
>  def initialize(p1)    # p1 is an int
>    puts("do it like Beckham")
>  end
>
>  def initialize(p2)     # p2 is a string
>    puts("do it like Ronaldo")
>  end
>
> I understand of course that this can't work in ruby without strong
> typing.

[snip]

> So please tell me, what is the ruby way to handle this kind of  
> problem?
> Use a single parameter and reflection?

We can ask for a variable number of arguments, then check for the  
various options.  Something like:

def initialize( *args )
     if args.empty?
         puts "no param"
     elsif args.size == 1 and args.first.is_a? Integer
         puts "do it like Beckham"
     elsif args.size == 1 and args.first.is_a? String
         puts "do it like Ronaldo"
     else
         raise ArgumentError, "Invalid initialization for # 
{self.class}."
     end
end

Hope that helps.

James Edward Gray II