Keyword Arguments (**kwargs)
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: