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

Keyword Arguments (**kwargs)

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")
🔒

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.