Keyword arguments let you give names to inputs when calling a method. This makes your code easier to read and understand.
0
0
Keyword arguments in Ruby
Introduction
When a method needs many inputs and you want to avoid confusion about their order.
When you want to make some inputs optional with default values.
When you want to clearly show what each input means in your code.
When you want to improve code readability for others or your future self.
Syntax
Ruby
def method_name(arg1:, arg2: default_value) # method body end method_name(arg1: value1, arg2: value2)
Keyword arguments are written with a colon after the name in the method definition.
You call the method by naming each argument, like arg1: value.
Examples
This method requires both
name and age as keyword arguments.Ruby
def greet(name:, age:) puts "Hello, #{name}! You are #{age} years old." end greet(name: "Alice", age: 30)
Here,
age has a default value of 18, so you can skip it when calling.Ruby
def greet(name:, age: 18) puts "Hello, #{name}! You are #{age} years old." end greet(name: "Bob")
This method shows how to use a default value for
size.Ruby
def order(drink:, size: "medium") puts "You ordered a #{size} #{drink}." end order(drink: "coffee")
Sample Program
This program defines a method to book a flight using keyword arguments. It shows how to use default values and how to call the method with different arguments.
Ruby
def book_flight(destination:, date:, seat_class: "economy") puts "Booking a #{seat_class} seat to #{destination} on #{date}." end book_flight(destination: "Paris", date: "2024-07-01") book_flight(destination: "Tokyo", date: "2024-08-15", seat_class: "business")
OutputSuccess
Important Notes
If you forget to provide a required keyword argument, Ruby will raise an error.
Keyword arguments improve code clarity by naming each input explicitly.
Summary
Keyword arguments let you name inputs when calling methods.
You can set default values to make some arguments optional.
This makes your code easier to read and less error-prone.