0
0
RubyHow-ToBeginner · 3 min read

How to Use Keyword Arguments in Ruby: Syntax and Examples

In Ruby, you use keyword arguments by defining method parameters with names and calling the method with those named arguments. This makes your code clearer and lets you pass arguments in any order using def method_name(arg1:, arg2:) and calling with method_name(arg2: value, arg1: value).
📐

Syntax

Keyword arguments are defined by naming parameters with a colon : after each name in the method definition. When calling the method, you pass arguments by specifying the parameter name followed by a colon and the value.

This syntax allows arguments to be passed in any order and improves code readability.

ruby
def greet(name:, age:)
  puts "Hello, #{name}! You are #{age} years old."
end
💻

Example

This example shows a method using keyword arguments and how to call it with arguments in any order.

ruby
def order_coffee(size:, type:, sugar: 0)
  puts "Order: #{size} #{type} coffee with #{sugar} sugar(s)."
end

order_coffee(type: 'Latte', size: 'Large', sugar: 2)
order_coffee(size: 'Small', type: 'Espresso')
Output
Order: Large Latte coffee with 2 sugar(s). Order: Small Espresso coffee with 0 sugar(s).
⚠️

Common Pitfalls

One common mistake is forgetting to provide all required keyword arguments, which raises an error. Another is mixing positional and keyword arguments incorrectly.

Also, if you want keyword arguments to be optional, you must provide default values.

ruby
def book_flight(destination:, date:)
  puts "Flight to #{destination} on #{date}."
end

# Wrong: missing keyword argument 'date'
# book_flight(destination: 'Paris') # raises ArgumentError

# Correct with default value

def book_flight(destination:, date: 'TBD')
  puts "Flight to #{destination} on #{date}."
end

book_flight(destination: 'Paris')
Output
Flight to Paris on TBD.
📊

Quick Reference

  • Define keyword arguments with name: in method parameters.
  • Call methods using name: value pairs.
  • Provide default values to make keyword arguments optional.
  • Keyword arguments improve clarity and flexibility.

Key Takeaways

Define keyword arguments by naming parameters with colons in method definitions.
Call methods using named arguments in any order for clearer code.
Provide default values to make keyword arguments optional and avoid errors.
Missing required keyword arguments causes an ArgumentError.
Keyword arguments improve readability and flexibility in method calls.