9

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

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

我怎样才能防止这种情况发生?有没有防泼溅之类的东西?

4

2 回答 2

4

这是在 Ruby 2.0.0-p247 中修复的错误,请参阅此问题

于 2013-03-18T18:08:00.217 回答
1

关于什么

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

?

于 2013-03-18T17:24:34.450 回答