Splat vs Double Splat in Ruby: Key Differences and Usage
* (splat) is used to capture or expand arrays in method arguments, while ** (double splat) handles hashes or keyword arguments. The splat deals with positional arguments, and the double splat deals with named keyword arguments.Quick Comparison
Here is a quick side-by-side comparison of splat and double splat in Ruby.
| Feature | Splat (*) | Double Splat (**) |
|---|---|---|
| Purpose | Handles multiple positional arguments as an array | Handles multiple keyword arguments as a hash |
| Usage in Method Parameters | Collects extra positional arguments | Collects extra keyword arguments |
| Usage in Method Calls | Expands an array into positional arguments | Expands a hash into keyword arguments |
| Data Type Handled | Array | Hash |
| Introduced In | Ruby 1.9+ | Ruby 2.0+ |
Key Differences
The * operator, known as splat, is used to work with positional arguments in methods. When placed before a parameter, it collects all remaining positional arguments into an array. When used in a method call, it expands an array into individual arguments.
On the other hand, the ** operator, called double splat, is designed for keyword arguments. It collects extra keyword arguments into a hash when used in method parameters, and expands a hash into keyword arguments when used in method calls.
While splat deals with ordered arguments, double splat deals with named arguments, making it easier to handle flexible method signatures with keywords. Also, double splat requires Ruby 2.0 or newer, while splat has been around since Ruby 1.9.
Code Comparison
Here is an example showing how splat * handles multiple positional arguments:
def greet(*names)
names.each { |name| puts "Hello, #{name}!" }
end
greet('Alice', 'Bob', 'Carol')Double Splat Equivalent
This example shows how double splat ** handles keyword arguments as a hash:
def describe_person(**info)
info.each { |key, value| puts "#{key}: #{value}" }
end
describe_person(name: 'Alice', age: 30, city: 'NYC')When to Use Which
Choose * (splat) when you want to accept or pass a flexible number of positional arguments as an array. Use it when the order of arguments matters and they are unnamed.
Choose ** (double splat) when you want to accept or pass keyword arguments as a hash. Use it when argument names matter and you want to handle optional named parameters cleanly.
Key Takeaways
* to handle multiple positional arguments as an array.** to handle multiple keyword arguments as a hash.