I'd like to have a method that accepts a hash and an optional keyword argument. I tried defining a method like this:
我想要一个接受哈希和可选关键字参数的方法。我尝试定义这样的方法:
def foo_of_thing_plus_amount(thing, amount: 10)
thing[:foo] + amount
end
When I invoke this method with the keyword argument, it works as I expect:
当我使用关键字参数调用此方法时,它按预期工作:
my_thing = {foo: 1, bar: 2}
foo_of_thing_plus_amount(my_thing, amount: 20) # => 21
When I leave out the keyword argument, however, the hash gets eaten:
但是,当我省略关键字参数时,哈希会被吃掉:
foo_of_thing_plus_amount(my_thing) # => ArgumentError: unknown keywords: foo, bar
How can I prevent this from happening? Is there such a thing as an anti-splat?
我怎样才能防止这种情况发生?有没有像防啪啪一样的东西?
2 个解决方案
#1
#2
1
What about
关于什么
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
?
?
#1
#2
1
What about
关于什么
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
?
?