[Talking-Ruby] Positional and keyword arguments in Ruby
Positional arguments, optional arguments, and keyword arguments.
1 | # a is an positional argument. |
Splat Operators
*
is called splat, and **
is called double splat. You can use these operators in method signatures and method calls:
In method signatures
-
Single splat (*) packs the argument into Array.
-
Double splat (**) packs the argument into Hash.
1 | def a_method(*args) |
In method calls
-
Single splat (*) unpacks the argument from Array.
-
Double splat (**) unpacks the argument from Hash.
1 | def a_method(a, b) |
Keyword Arguments
Keyword arguments first introduced in Ruby 2.0 - https://www.ruby-lang.org/en/news/2013/02/24/ruby-2-0-0-p0-is-released/. Block keyword arguments also introduced:
1 | # Keyword arguments first introduced in Ruby 2.0. |
Ruby < 2.0
Before Ruby 2, we use options Hash to achieve keyword arguments, and Hash#fetch
for required keyword arguments:
1 | def ruby_19_translate(options = {}) |
Automatic Conversion
Ruby < 2.7
If the last argument of a method call is a Hash, Ruby < 2.7 will automatically convert to Keyword Arguments.
1 | def method_last_hash(a:) |
Ruby 2.7
Upgrade to Ruby 2.7 and fix the places rely on such automatic conversion.
- Be explicit. Wrap argument in
{}
if you want to pass in a hash:
1 | def translate(key: "en") |
- Prefix argument with
**
if you want to pass in keywords:
1 | def translate(key: "en") |
Use double splat keyword arguments instead of options hash:
1 | def good(**kwargs) |
Support for **nil
Ruby 2.7 added support for **nil to explicitly mention if a method doesn’t accept any keyword arguments in method call.
1 | def sum(a, b, **nil) |
To suppress above deprecation warnings we can use -W:no-deprecated
option.
References
[3] Ruby 3 Keyword Arguments — Juanito Fatas - https://juanitofatas.com/ruby-3-keyword-arguments