Keyword Arguments (**kwargs)
Keyword arguments let you label each input by name when calling a method, like writing 'size: large' on an order form. The order no longer matters and it is easy to read.
In this page:
Syntax
def method_name(name:, option: default_value)
# body
end
method_name(name: value, option: other_value)
def other_method(**kwargs)
# kwargs is a hash
end
Keyword Arguments (**kwargs)
Ruby supports named keyword arguments, def configure(name:, timeout: 30), which must be passed by name at the call site rather than by position, improving readability for methods with many parameters.
**kwargs collects any number of extra keyword arguments into a hash, similar to how *args collects positional ones. Keyword arguments without a default are required and raise an error if omitted.
Note:
- Keyword arguments make call sites self-documenting, e.g.
connect(host: "localhost", port: 8080)is clearer than two positional values.
Example: Keyword Arguments (**kwargs)
def configure(name:, timeout: 30)
puts "Name: #{name}, Timeout: #{timeout}"
end
configure(name: "server1")
configure(name: "server2", timeout: 60)
def show_options(**options)
puts options.inspect
end
show_options(color: "red", size: "large")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Passing keyword arguments positionally, as in
configure("server1"), which raisesArgumentErrorsince Ruby 3. - Forgetting a required keyword like
name:, which raisesArgumentError (missing keyword: :name). - Misspelling a keyword such as
timeot: 60, which raisesunknown keyword.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: