This is a bug that was fixed in Ruby 2.0.0-p247, see this issue.
How can I prevent a positional argument from being expanded into keyword arguments?
-
24-03-2022 - |
Question
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?
Solution
OTHER TIPS
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
?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow