Ruby variable arguments, also known as varargs, allow methods to accept a flexible number of arguments. This powerful feature enhances the versatility of your Ruby code.
In Ruby, you can define a method that accepts any number of arguments using the splat operator (*
). This operator collects all extra arguments into an array.
def method_name(*args)
# Method body
end
Here, *args
captures all arguments passed to the method as an array.
Let's explore some practical examples of how to use variable arguments in Ruby:
def sum(*numbers)
numbers.reduce(0, :+)
end
puts sum(1, 2, 3, 4, 5) # Output: 15
puts sum(10, 20) # Output: 30
In this example, the sum
method can accept any number of arguments and calculate their sum.
def print_items(*items)
items.each { |item| puts item }
end
print_items("Apple", "Banana", "Cherry")
# Output:
# Apple
# Banana
# Cherry
This method demonstrates how variable arguments can be used to print an arbitrary number of items.
You can mix regular parameters with variable arguments in Ruby methods:
def greet(name, *messages)
puts "Hello, #{name}!"
messages.each { |msg| puts msg }
end
greet("Alice", "How are you?", "Nice to meet you!")
# Output:
# Hello, Alice!
# How are you?
# Nice to meet you!
In this case, name
is a required parameter, while *messages
captures any additional arguments.
Ruby 2.7 introduced argument forwarding, allowing you to pass variable arguments to another method easily:
def wrapper_method(...)
another_method(...)
end
This feature is particularly useful when creating wrapper methods or delegating calls.
Variable arguments in Ruby provide a flexible way to handle methods with an unknown number of parameters. They are especially useful when creating utility functions, wrappers, or methods that need to adapt to different input scenarios. By mastering variable arguments, you can write more versatile and reusable Ruby code.
For more information on related topics, check out Ruby Method Arguments and Ruby Default Arguments.