Search code examples
rubynew-operatorinitializer

`initialize` seems to check the arguments given to `new`


I am looking at this code:

class Mo
  def new(indy, rome = 1)
    initialize(indy, rome)
  end
  def initialize(indy, rome)
    ...
  end
end

Mo.new(2)

I get this output:

test.rb:6:in `initialize': wrong number of arguments (1 for 2)   (ArgumentError)

If I add the default value for rome in the definition to new, it works:

class Mo
  def new(indy, rome = 1)
    initialize(indy, rome)
  end
  def initialize(indy, rome = 1)
    ...
  end
end

Mo.new(2)

Why?


Solution

  • Because Mo.new(2) calls the method Mo.new, which by default calls the method Mo#initialize with the single argument 2 that it received, but your Mo#initialize expects two arguments.