← Back to Ruby Course | Chapter 7: Methods | Lesson 5 of 7

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.
Syntax
ruby
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)

markup
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")
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
  1. Passing keyword arguments positionally, as in configure("server1"), which raises ArgumentError since Ruby 3.
  2. Forgetting a required keyword like name:, which raises ArgumentError (missing keyword: :name).
  3. Misspelling a keyword such as timeot: 60, which raises unknown keyword.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.