调用super时参数数量错误

时间:2012-08-02 20:56:44

标签: ruby

class A
  def initialize
    print "Hello! "
  end
end

class B <  A
  def initialize(name)
    super
    print "My name is #{name}!"
  end
end

test = B.new("Fred")

我得到了

wrong number of arguments (1 for 0)

但为什么呢?类B需要一个参数,我正在给它一切。类A不需要任何参数,因此我根本没有通过super传递任何内容。

1 个答案:

答案 0 :(得分:18)

你需要使用super()才能在没有参数的情况下调用它。超级本身会自动使用提供给自身的参数调用父级(即“名称”)

相关问题