5

is there a way to have multiple “initialize” methods in ruby? For example: one method excepting one argument while another excepts three ?

Something like

 class One
  def initialize (a)
    puts a
  end
  def initialize_1 (a,b)
    puts a ,b 
  end
end
13driver
  • 237
  • 2
  • 5
  • 10
  • 2
    I agree with ramblex. Also relevant - http://stackoverflow.com/questions/9373104/why-does-ruby-not-support-method-overloading. If there is a specific problem you're trying to solve, you might try posting a more specific question as there may be a different way to go about it. – Scott S Mar 22 '13 at 15:06
  • thanks, there is no specific problem im just trying to figure out the ins and outs of the language. I understand that the answer is no but im still not sure how you get around that . – 13driver Mar 22 '13 at 15:11
  • you could achieve the effect with `konstructor` gem https://github.com/snovity/konstructor, e.g. you would have just to declare `konstructor :initialize_1` – snovity Jan 26 '17 at 07:26

1 Answers1

5

initialize is actually not a constructor. You can indeed have two constructors.

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
sawa
  • 165,429
  • 45
  • 277
  • 381
  • What does this buy you? Everything still funnels through the original new and the one initialize. Might as well say `def self.new_1(a,b); new(a,b); end` without the complexity of the aliasing goo. It is common to have alternative constructors with different names that repackage their args into a general form for the base new. – dbenhur Mar 22 '13 at 16:05
  • we meet again , aren't you are the guy who gave me such a lovely explanation of how `self` works ? Anyway this still complains 'wrong number of arguments' whenever I send it more then one argument . Also im not sure what this gets me ... – 13driver Mar 22 '13 at 17:09