【问题标题】:Why doesn't a proc care about the number of arguments?为什么proc不关心参数的数量?
【发布时间】:2016-11-20 17:49:36
【问题描述】:
def method1(&proc)
  proc.call(1,2,3)
end

method1{ |x,y,z,a| puts a}

不抛出任何错误并输出nil

为什么它不检查参数?其背后的逻辑是什么?

【问题讨论】:

  • Ruby documentation for proc 说“由 proc 生成的 Proc 对象忽略了额外的参数...它为缺少的参数提供 nil。”。这就是你的情况。

标签: ruby proc


【解决方案1】:

Proc 不关心验证正确数量的参数,但 lambda 会...

def method1(&proc)
  proc.call(1,2,3)
end

method1 { |x,y,z,a| puts a}
method1 lambda { |x,y,z,a| puts a }

结果:

lambda.rb:1:in `method1': wrong number of arguments (given 1, expected 0) (ArgumentError)
    from lambda.rb:6:in `<main>'

来自ruby docs

对于使用 lambda 或 ->() 创建的 proc,如果将错误数量的参数传递给具有多个参数的 Proc,则会生成错误。对于使用 Proc.new 或 Kernel.proc 创建的 proc,额外的参数会被静默丢弃。

【讨论】:

  • @InQusitive :我自己没有使用过这个功能,但它可能对元编程模式有一些用处。
猜你喜欢
  • 2011-04-24
  • 2020-12-08
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 2023-03-23
  • 1970-01-01
  • 2012-06-08
相关资源
最近更新 更多