After almost 8 months of working with Ruby, it still offers something new every day. Here’s a tricky part about overriding a constructor without any arguments:

class A
  def initialize
    @foo = 123
  end
end

class B < A
  def initialize(special_argument)
    # This call will result in "wrong number of arguments (1 for 0)"
    # exception because Ruby automatically passes all arguments.
    super
    # ... the same as ...
    super(*args)

    # Special case of calling super class' constructor without
    # argument - you MUST include parentheses to indicate
    # that you aren't passing any arguments.
    super()
  end
end

Obviously, I would’ve known that if I read the manual, but it would be too easy.

One Response to “Learning Ruby: A little trick to overriding parameterless constructors”
  1. Coletânea de Links | Blog do Urubatan Says:

    […] aprendendo Ruby, e precisa sobrescrever um método que tinha um número diferente de parâmetros, este post mostra como fazer isto sem receber […]

Leave a Reply