Keyword arguments and forwarding

Required and optional keywords

A keyword argument is named at the call site, so the reader knows what each value means without opening the method. A keyword with no default is required; a keyword with a default is optional:

def greet(name:, greeting: "Hello") "#{greeting}, #{name}" end puts greet(name: "Ada") puts greet(name: "Ada", greeting: "Hi")

ruby greet_demo.rb

Hello, Ada
Hi, Ada

Calling without the required keyword raises before the method body runs, and the message names the missing one:

ruby -e 'def f(a:) = a; f'

-e:1:in 'f': missing keyword: :a (ArgumentError)
  from -e:1:in '<main>'

Collecting the rest with **

**rest collects the keywords the method does not name, which lets a wrapper pass options through without listing them:

ruby -e 'def f(a:, b: 2, **kw) = [a, b, kw]; p f(a: 1, c: 3)'

[1, 2, {c: 3}]

The result is an array of the two named values and a hash of the rest. Ruby 3.4 prints the hash in the short form, {c: 3}, the same change lesson 8.8, later in the course, showed for p.

A trailing hash and a keyword call are not interchangeable in Ruby 3. A method that declares keywords does not accept a hash: total(options) raises ArgumentError, and the hash has to be splatted with **options. The other direction is what keeps old code working: keywords passed to def f(opts = {}) still arrive as one positional hash.

def total(price:, tax: 0) price + tax end options = {price: 100, tax: 7} puts total(**options)

ruby kwargs_hash.rb

107

Passing the hash itself is refused, and the message names the keyword it expected:

ruby -e 'def total(price:) = price; total({price: 1})'

-e:1:in 'total': wrong number of arguments (given 1, expected 0; required keyword: price) (ArgumentError)
  from -e:1:in '<main>'

Forwarding with ...

A method that adds a step and calls another one should forward everything it received: positionals, keywords and the block. ... does exactly that, and it is shorter than spelling out all three:

def inner(a, b:) a + b end def outer(...) inner(...) end puts outer(1, b: 2)

ruby -e 'def inner(a, b:) = a + b; def outer(...) = inner(...); p outer(1, b: 2)'

3

Before Ruby 2.7 the same wrapper needed def outer(*args, **kwargs, &block) and a call with three splats. ... is the version to write now, and it also forwards a block the wrapper never names.

What to watch for

A keyword and a positional argument with the same name are two different parameters. def f(x, x:) is legal and confusing; rename one of them.

A method with many optional keywords is a configuration object in disguise. When the list passes five, a small class or a Data value with defaults is easier to validate and to read.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What makes a keyword argument required?

    Answer

    It has no default value

    A keyword with a default is optional; a keyword with no default must be passed at every call.

  2. What does this program print? def greet(name:, greeting: "Hello") "#{greeting}, #{name}" end puts greet(name: "Ada") puts greet(name: "Ada", greeting: "Hi")

    Answer

    Hello, Ada / Hi, Ada

    The second call overrides the default greeting, the first one takes it.

  3. What does **rest in a parameter list collect?

    Answer

    The keywords the method does not name, as one hash

    The named keywords go to their own parameters; the rest become one hash.

  4. What does this program print? def f(a:, b: 2, **kw) = [a, b, kw] p f(a: 1, c: 3)

    Answer

    [1, 2, {c: 3}]

    a is 1, b keeps its default 2, and c lands in the rest hash; Ruby 3.4 prints a symbol key in the short form.

  5. What does this program raise? def f(a:) = a f

    Answer

    ArgumentError, because the keyword :a is missing

    The call is refused before the body runs, and the message is missing keyword: :a (ArgumentError).

  6. What does def outer(...) forward to the method it calls?

    Answer

    Positionals, keywords and the block

    ... stands for all three, including a block the wrapper never names.

  7. A method is defined as def total(price:, tax: 0). Which call works?

    Answer

    total(**{price: 1})

    A hash is not converted to keywords in Ruby 3, so it has to be splatted with **; a plain hash and an extra keyword both raise.

  8. What does this program print? def inner(a, b:) a + b end def outer(...) inner(...) end puts outer(1, b: 2)

    Answer

    3

    outer forwards 1 and b: 2 to inner unchanged, and 1 + 2 is 3.

  9. What is true of def f(x, x:)?

    Answer

    It is legal, and confusing enough that one of the two should be renamed

    A positional and a keyword parameter with one name are two different parameters.

  10. A method has grown eight optional keywords. What does the lesson suggest?

    Answer

    A small class or a Data value with defaults, easier to validate and read

    A long keyword list is a configuration object in disguise, and a value object gives it a name and a place to validate.

Article author: Arthur Isaev