Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何防止位置参数扩展为关键字参数?_Ruby_Arguments_Ruby 2.0_Keyword Argument - Fatal编程技术网

Ruby 如何防止位置参数扩展为关键字参数?

Ruby 如何防止位置参数扩展为关键字参数?,ruby,arguments,ruby-2.0,keyword-argument,Ruby,Arguments,Ruby 2.0,Keyword Argument,我希望有一个接受哈希和可选关键字参数的方法。我尝试定义这样一种方法: 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 但是,当我省略关键字参数时,哈希会被吃掉:

我希望有一个接受哈希和可选关键字参数的方法。我尝试定义这样一种方法:

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
我怎样才能防止这种情况发生?有没有反splat这样的东西?

怎么办

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

这是Ruby 2.0.0-p247中修复的一个bug,请参阅。

相关问题提到了后移植。实际上,这对我意味着什么?我能以某种方式更新我的ruby 2.0.0-p247版本吗?或者这是否意味着他们在这之后发布的2.0.0-pX的任何版本都会得到修复?谢谢。至少我现在知道了一个解决方法:每次都使用关键字参数。相当烦人。这适用于OP的假设示例。但是,如果原始方法定义包含多个可选关键字参数,那么示例行(结果为21)将在接收的
opt
参数中删除它们,因为只传递
amount
键。事实上,我当前的用例是一个假设的例子,所以这很有帮助。