调用super时参数数量错误

时间:2022-01-07 18:56:35
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")

And I get

我明白了

wrong number of arguments (1 for 0)

But why? Class B requires one argument, and I am giving it all right. Class A doesn't require any argument, so I am not passing anything through super at all.

但为什么? B级需要一个参数,我正在给它。 A级不需要任何参数,所以我根本没有通过super传递任何东西。

1 个解决方案

#1


18  

You need to use super() in order to call it with no arguments. Super by itself automatically calls the parent with the arguments provided to itself (ie. "Name")

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

#1


18  

You need to use super() in order to call it with no arguments. Super by itself automatically calls the parent with the arguments provided to itself (ie. "Name")

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