Capturing undeclared keyword arguments double splat

suggest change

The ** 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!" }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents