RUBY / CHAPTER 04
Keyword arguments and explicit options
IntermediateMake call-site intent readable without losing argument contracts.
By the end of this chapter
- Distinguish positional and keyword arguments
- Use defaults deliberately
- Forward keywords explicitly
The idea
Keyword arguments name their meaning at the call site. A required keyword has no default, while an optional keyword supplies a default when omitted. This can make configuration clearer than several adjacent booleans or integers whose positions are easy to confuse. A default is still a policy choice: it should describe a sensible missing-argument behavior, not silently override an explicitly supplied value.
Modern Ruby distinguishes keyword arguments from a positional hash. A wrapper that forwards arbitrary calls should preserve positional arguments, keywords, and the block as separate channels. Using **kwargs forwards keyword entries, while *args forwards positional entries. Document which options the public API accepts; swallowing unknown options can hide misspellings that would otherwise be reported as useful argument errors.
def total(values, minimum: 0, multiplier: 1)
values.select { |n| n >= minimum }.sum * multiplier
end
puts total([1,3,5], minimum: 3, multiplier: 2)16
The named threshold retains three and five, then the named multiplier doubles their total.
Try it yourself
Write a wrapper that forwards *args, **kwargs, and &block to another method without changing them.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING