Hi,
Is it possible to use multiple constructors in Ruby?
class SQLServerConnection
def initialize(server_name, db)
end
def initialize(server_name, db, user_name, password)
end
end
Thank You
Aidy
First of all initialize is not a constructor but an initializer,
behind the scenes the following happenes
class Object
def self.new *args, &blk
o = allocate
o.send :initialize, *args, &blk # this because #initialize is
*always* private
o
end
end
As you can see #initialize is an instance method and #new is a
singleton (or class) method.
Secondly, and that holds for all methods, #initialize is only an
example, you cannot "overload" method definitions but simulate that
behavior, in your case I would do the following
class SQLServerConnection
private
def initialize *args
case args.size
when 2
init_name_db *args
when 4
init_user_pw *args
else
error
end
end
def init_name_db server_name, db
...
end
def init_user_pwd server_name, db, user, pwd
...
end
end
HTH
Robert