--- Stephan Mueller <d454d / web.de> 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.
> 
> My next idea was to use named parameters:
> 
>  def initialize(p1=nil, p2=nil)
>    unless p1.nil?
>      ..
>    end
>    unless p2.nil?
>      ..
>    end
>  end
> 
>  # okay, let's make a baby!
>  MyClass.new(p1=500)
>  
> 
> But as far as I could see in the pickaxe, there are no named
> parameters
> in ruby (1.8 at least), right?
> 
> So please tell me, what is the ruby way to handle this kind
> of problem?
> Use a single parameter and reflection?


What you are talking about is really method overloading not
polymorphism in my opinion.

My take on the "ruby way" is to not overload methods by type
like you can easily do in java.  Instead you just make multiple
distinct methods with each method taking its own "type".  This
give maximal flexibility with duck-typing.

There is no reason you can't make multiple new type class
methods that call the normal "new" method - you wouldn't need
an initialize in that case.

The closest you can come to named parameters is by using a hash
(right now, at least):

def test(hash)
    if hash[:p1]
        ...
    elsif hash[:p2]
        ...
    end
end

test(:p1=>500)

In ruby 1.9 you can use the shortcut test(p1: 500) when you
want the key to be a symbol.



		
____________________________________________________
Start your day with Yahoo! - make it your home page 
http://www.yahoo.com/r/hs