liveBook · Manning

Required argument

As explained in The Well-Grounded Rubyist, Fourth Edition

A required argument is a method input that must be supplied for a method call to be valid.

A required argument is a value a caller must supply for a method call to be valid. In `def obj.c2f(c)`, `c` is a formal parameter; in `obj.c2f(100)`, `100` is its argument. The call assigns that value to `c` for use inside the method. section 2.1.3

When the count does not match

`def obj.two_required_args(x, y)` requires two values. `obj.two_required_args(3, 4)` supplies them; `obj.two_required_args(1, 2, 3)` raises `ArgumentError` for giving three where two were expected. section 2.4.1

Required parameters can share a signature with optional ones. In `def two_or_more(a, b, *c)`, `a` and `b` must receive values; `*c` collects any extras into an array, or receives `[]` when there are none. A default-valued parameter such as `c=1` is optional instead: its default applies only when the caller omits that value. section 2.4.1

Position matters, but a starred parameter does not claim values needed by required parameters after it. For `def mixed_args(a, b, *c, d)`, the call `mixed_args(1, 2, 3, 4, 5)` assigns `a=1`, `b=2`, `c=[3, 4]`, and `d=5`. With only three values, `d` receives the last one and `c` is empty. Keep optional parameters between required parameters where the signature permits them; `def broken_args(x, *y, z=1)` is a syntax error. section 2.4.2 section 2.4.3

A keyword can be required too. In `def m(a:, b:)`, the trailing colons declare required keyword parameters: `m(a: 1, b: 2)` works, while omitting either keyword raises `ArgumentError`. Writing `a: 1` in the definition instead gives that keyword a default. Positional and keyword requirements can coexist in one signature. section 9.3.8

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through argument-count errors and binding order with defaults and starred parameters, then extends the distinction to keywords.
Examples
Uses a temperature-conversion call, argument-count errors, mixed-parameter calls, and missing-keyword errors.
What it assumes
Introduces parameters and call arguments directly; defers the fuller account of keyword arguments until after hashes.
What you can do after
Build it from scratch: define Ruby methods with required inputs and predict how calls bind values or fail.
How it connects
Connects method calls and local variables to optional parameters, default values, starred parameters, and keyword arguments.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.