Multiple constructors

Lars M. wrote:

Hi,

Is there a way to have two constructors which take a
different number
of
arguments?

Multiple constructors are a plague that needs to be wiped from the Good Land
of Ruby.

Either use default values:

def initialize(a,b=nil,c=nil)
#handle a,b,c
end

Or use named arguments

def initialize(args={})
#handle args
end

I hate seeing new1, new2, new3, etc (except for C extensions, where I
realize they’re pretty much unavoidable) for a few reasons:

  1. It forces me to look up the documentation every time - there’s no way
    I’ll remember the difference between new1, new2, and new3
  2. It’s less readable than, say, named arguments, especially as your
    argument list gets longer
  3. I hate passing nil to a method when I really only need to pass 1 or 2
    arguments to a 4 argument constructor, e.g. foo(“one”,nil,nil,“two”)
  4. At some point down the road, you may want to pass another arugument you
    hadn’t thought of originally. What are you going to do then? Add yet
    another
    constructor?

Just my .02

Dan