Multiple constructors, thanks!

Thanks very much to all for the great info on this topic!

Christopher J. Meisenzahl CPS, CSTE
Senior Software Testing Consultant
Spherion
christopher.j.meisenzahl@citicorp.com

···

-----Original Message-----
From: nat.pryce [mailto:nat.pryce@b13media.com]
Sent: Thursday, November 21, 2002 10:53 AM
To: ruby-talk
Subject: Re: Multiple constructors?

On Thu, 2002-11-21 at 15:06, christopher.j.meisenzahl@citicorp.com > wrote:

I’ve seen how Ruby uses an initialize() method as a constructor.

Can this method be overloaded? After playing with IRB I’m
assuming it
can’t

In Ruby there are actually two methods that act as a
constructor, the new method of the class and the initialize
method of the object. The new method allocates a new object
and then calls initialize on it.

If you want to define multiple constructors, define multiple
“new” methods on your class and have those call different
“initialize” methods on the object.

For example the following code will print:

“initialize 1”
“initialize 2”

class C
def C.new_1()
c = C.new()
c.initialize_1()
c
end

def C.new_2()
    c = C.new()
    c.initialize_2()
    c
end

def initialize_1()
    p "initialize 1"
end

def initialize_2()
    p "initialize 2"
end

end

c1 = C.new_1()
c2 = C.new_2()

Cheers,
Nat.


Nat Pryce nat.pryce@b13media.com
B13media