在ruby中有多个构造函数

13d*_*ver 5 ruby constructor initialization

有没有办法在ruby中有多个"初始化"方法?例如:一个方法除了一个参数而另一个方法除了三个?

就像是

 class One
  def initialize (a)
    puts a
  end
  def initialize_1 (a,b)
    puts a ,b 
  end
end
Run Code Online (Sandbox Code Playgroud)

saw*_*awa 5

initialize实际上不是构造函数.你确实可以有两个构造函数.

class One
  singletonclass.class_eval{alias old_new :new}
  def self.new a
    puts a
    old_new
  end
  def self.new_1 a, b
    puts a, b
    old_new
  end
end
Run Code Online (Sandbox Code Playgroud)