Wednesday, January 28, 2015

super vs super() in Ruby

class A
  attr_reader :stack

  def initialize
    @stack = Array.new
  end
end

class B < A
  attr_reader :name

  def initialize(args={})
    super
    @name = args.fetch(:name, nil)
  end
end

When I ran the following code, I got an ArgumentError
b = B.new({:name => 'Ruby'})

ArgumentError: wrong number of arguments (1 for 0)
The error complained that I was passing in 1 argument for the initialize method in class A. The reason the ArgumentError appears is super in the subclass will take with it any parameters that were sent to the initialize method. To avoid sending the parameters, call super with parentheses. Thus, the initialize method for class B should be

def initialize(args={})
  super()
  @name = args.fetch(:name, nil)
end

No comments:

Post a Comment