Capturing undeclared keyword arguments double splat
suggest changeThe ** operator works similarly to the \* operator but it applies to keyword parameters.
def options(required_key:, optional_key: nil, **other_options)
other_options
end
options(required_key: 'Done!', foo: 'Foo!', bar: 'Bar!')
#> { foo: "Foo!", bar: "Bar!" }
In the above example, if **other_options is omitted, Ruby raises ArgumentError. On current Ruby the message is unknown keywords: :foo, :bar.
def without_double_splat(required_key:, optional_key: nil)
# do nothing
end
without_double_splat(required_key: 'Done!', foo: 'Foo!', bar: 'Bar!')
#> ArgumentError: unknown keywords: :foo, :bar
This is handy when you have a hash of options that you want to pass to a method and you do not want to filter the keys. Since Ruby 3, a plain hash is a positional argument, so unpack it with **:
def options(required_key:, optional_key: nil, **other_options)
other_options
end
my_hash = { required_key: true, foo: 'Foo!', bar: 'Bar!' }
options(**my_hash)
#> { foo: "Foo!", bar: "Bar!" }
It is also possible to unpack a hash with the ** operator. That lets you pass keywords directly, in addition to values from other hashes:
my_hash = { foo: 'Foo!', bar: 'Bar!' }
options(required_key: true, **my_hash)
#> { foo: "Foo!", bar: "Bar!" }
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents