带有初始化的参数错误 [英] Argument error with initialize

查看:113
本文介绍了带有初始化的参数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以下代码:

class A
  def initialize foo = nil
    super
  end
end

A.new

当我运行它时,它会在super行上引发错误wrong number of arguments (1 for 0).为什么这会引发错误?我尚未将任何参数传递给newsuper,并且不确定为什么.如果我省略了可选的参数签名foo = nil,该错误就会消失.

When I run it, it raises an error wrong number of arguments (1 for 0) at the super line. Why does this raise an error? I haven't passed any argument to new or super, and am not sure why. If I omit the optional argument signature foo = nil, the error goes away.

上面带有super的代码可能没有多大意义,但是在实际使用中,AHash的子类,并且我有一个传递给super的块.

The code above with super might not make much sense, but in actual use, A is a subclass of Hash, and I have a block passed to super.

推荐答案

之所以会出现此问题,是因为当您在不指定参数的情况下调用super时,它会使用与调用方收到的参数相同的参数来调用父方法. 在您的情况下,仅调用super与调用super(foo)相同,并且Object类(A的父对象)不包含接收参数的初始化程序. 我相信您可以从以下代码中获得满意的效果:

It raises because when you call super without specifying arguments, it calls the parent method with the same arguments that the caller received. In your case, calling just super is the same as calling super(foo), and the Object class (the parent object of A) contains no initializer receiving a parameter. I believe you expect the behavior from this code:

class A
  def initialize foo = nil
    super() # <= note the empty parentesis
  end
end

A.new

请务必注意,即使默认值为nil,具有默认值的参数仍然是参数.默认值仅表示调用者可以在不指定参数的情况下调用它,而不表示该参数不存在.对于Ruby VM,您的初始化程序将始终具有foo参数.

It's important to note that an argument with default value is still an argument, even if the default value is nil. A default value only means that callers can call it without specifying the argument, not that the parameter does not exists. For the Ruby VM, your initializer will always have the foo argument.

您可以在irb会话中编写以下代码来验证此行为:

You can verify this behavior writing the following code in a irb session:

def foo(bar = nil); end
method(:foo).parameters # => [[:opt, :bar]]

这篇关于带有初始化的参数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆