Ruby 3.0 Keyword and Positional Arguments - TL;DR
I appreciate technical notes.
Here is a summary for posterity (i.e. me in the future.)
Keyword Arguments
# to use keyword arguments do:
foo(k: expr) # or
foo(**expr) # double splat
# with the definitions:
def foo(k: default) # or
def foo(k:) # or
def foo(**kwargs)
Not Recommended:
# please don't do this anymore, even though it will work
def foo(kwargs = {})
kwargs
end
foo(k: 1) #=> {:k=>1}
# please do this instead:
def foo(**kwargs)
kwargs
end
foo(k: 1) #=> {:k=>1}
Delegation
Must explicitly delegate:
# for ruby 3:
def foo(*args, **kwargs, &block)
target(*args, **kwargs, &block)
end
Watch out
- If you’re passing non-symbol keys as keyword arguments:
def foo(**kwargs)
kwargs
end
foo("key" => 42)
- Double splat with an empty hash (*{}) ```rb def foo(args) args end
empty_hash = {} foo(**empty_hash) #=> Ruby 2.6 or before: [{}] #=> Ruby 2.7 or later: []
3. The no-keyword-arguments syntax (**nil) is introduced
```rb
def foo(*args, **nil)
end
foo(k: 1)
#=> Ruby 2.7 or later: no keywords accepted (ArgumentError)
Written on May 10, 2024