【问题标题】:How can I prevent a positional argument from being expanded into keyword arguments?如何防止位置参数被扩展为关键字参数?
【发布时间】:2013-03-06 23:46:51
【问题描述】:

我想要一个接受散列和可选关键字参数的方法。我尝试定义这样的方法:

def foo_of_thing_plus_amount(thing, amount: 10)
  thing[:foo] + amount
end

当我使用关键字参数调用此方法时,它会按预期工作:

my_thing = {foo: 1, bar: 2}
foo_of_thing_plus_amount(my_thing, amount: 20) # => 21

但是,当我省略关键字参数时,哈希会被吃掉:

foo_of_thing_plus_amount(my_thing) # => ArgumentError: unknown keywords: foo, bar

如何防止这种情况发生?有没有防溅之类的东西?

【问题讨论】:

  • 谢谢。至少我现在知道一个解决方法:每次都使用关键字参数。很烦人。

标签: ruby arguments ruby-2.0 keyword-argument


【解决方案1】:

这是一个已在 Ruby 2.0.0-p247 中修复的错误,请参阅 this issue

【讨论】:

  • 链接的问题提到了反向移植。实际上,这对我意味着什么?我可以以某种方式更新我的 2.0.0-p247 版本的 ruby​​ 吗?或者这是否意味着他们在此之后发布的任何 2.0.0-pX 版本都可以修复?
【解决方案2】:

怎么样

def foo_of_thing_plus_amount(thing, opt={amount: 10})
  thing[:foo] + opt[:amount]
end

my_thing = {foo: 1, bar: 2}   # {:foo=>1, :bar=>2}
foo_of_thing_plus_amount(my_thing, amount: 20)   # 21
foo_of_thing_plus_amount(my_thing)   # 11

?

【讨论】:

  • 这适用于 OP 的假设示例。但是,如果原始方法定义包含多个可选关键字参数,则您的示例行(结果为 21)将在收到的 opt 参数中删除它们,因为只会传递 amount 键。事实上,我当前的用例是假设的例子,所以这会有所帮助。
猜你喜欢
  • 2020-06-19
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
相关资源
最近更新 更多