Hi --

On Fri, 22 Nov 2002, Paul Brannan wrote:

> 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).

Maybe you could do:

  def self.my_new
    obj = new
    class << obj; public :other_initialize; end
    obj.other_initialize
    class << obj; private :other_initialize; end
    obj
  end

  def other_initialize
    # ...
  end
  private :other_initialize


(give or take any hidden pitfalls I haven't spotted :-)


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav