4

I noticed some very strange behaviour in a class where I was accidentally calling super on a class with no superclass. Obviously I shouldn't have been calling super, but I found the Errors very odd:

class SomeClass

  def initialize(someparam)
    super
  end

end

Then:

SomeClass.new() # ArgumentError: wrong number of arguments (0 for 1)
SomeClass.new('cow') # ArgumentError: wrong number of arguments (1 for 0)

Why does the second Argument error occur and why doesn't a more specific error related to calling super on a non-existant superclass occur?

Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75
Undistraction
  • 42,754
  • 56
  • 195
  • 331

1 Answers1

4

SomeClass implicitly extends Object and Object has an implicit no-args initialize method.

Using super bare (i.e. with no args or parens) sends the superclass the same message as was received by the subclass. In your example, using super in SomeClass#initialize(arg) is actually sending #initialize(arg) to Object - hence the error.

The reason that there isn't a more specific error is that it isn't a special circumstance.

ireddick
  • 8,008
  • 2
  • 23
  • 21
  • 1
    Thanks. As an addition for clarification, calling super without parenthesis (as in my example) implicitly passes the arguments to the superclass's initialize method. Calling super() passes no arguments to superclass's initialize method and would prevent the error in this case. See http://stackoverflow.com/questions/2570428/constructor-overriding – Undistraction Jan 28 '13 at 23:38