What is the difference between positional arguments and keyword arguments in Ruby methods?
Last updated
Positional arguments match by order (
def f(a, b)). Keyword arguments match by name (def f(a:, b:)), can be passed in any order, and are self-documenting.Both can have defaults. A keyword without a default (
a:) is required.Since Ruby 3.0 they are fully separated: a Hash is no longer auto-converted to keywords, so pass it with explicit
**.
- https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/
- https://docs.ruby-lang.org/en/master/syntax/methods_rdoc.html
- https://buttondown.com/noelrap/archive
- https://noelrappin.com/2024/02/better-know-keyword-arguments/
- https://noelrappin.com/2024/01/better-know-positional-arguments/
- https://www.mintbit.com/blog/positional-and-keyword-arguments-in-ruby-on-rails/
- https://dev.to/just-the-v/the-simplest-guide-on-ruby-methods-arguments-25pk
- https://dev.to/montells/exploring-the-power-of-keyword-arguments-in-ruby-1gk8