On Fri, Nov 22, 2002 at 12:06:36AM +0900, 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?

Ruby does not have overloading.  As an alternative, you can do one of
the following:

1) Define initialize() like this:
     class Foo
       def initialize(*args)
         @host = @port = @filename = nil
         if args.length == 2 then
           @host = args[0]
           @port = args[1]
         elsif args.length == 1 then
           @filename = args[0]
         else
           raise ArgumentError, "Invalid number of arguments"
         end
       end
     end
   You can interpret args however you wish; it's an array containing all
   the arguments to your method.  You can also do your own type checking
   if you wish.

2) Define multiple constructors with different names:

     class Foo
       private_class_method :new

       # for lack of a better name
       def self.socket_new(host, port)
         obj = new()
         obj.initialize_with_host_and_port(host, port)
         return obj
       end

       # for lack of a better name
       def self.file_new(filename)
         obj = new()
         obj.initialize_with_filename(filename)
         return obj
       end

       def initialize
         @host = @port = @filename = nil
       end

       def initialize_with_filename(filename)
         @filename = filename
       end

       def initialize_with_host_and_port(host, port)
         @host = host
         @port = port
       end
     end

   the only thing I don't like about this second method is that
   initialize_with_filename and initialize_with_host_and_port are both
   public methods; I don't know any way to make them private
   (initialize() is always a private method).

Hope this gives you some ideas,

Paul