0
0
RubyComparisonBeginner · 3 min read

Splat vs Double Splat in Ruby: Key Differences and Usage

In Ruby, * (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.

FeatureSplat (*)Double Splat (**)
PurposeHandles multiple positional arguments as an arrayHandles multiple keyword arguments as a hash
Usage in Method ParametersCollects extra positional argumentsCollects extra keyword arguments
Usage in Method CallsExpands an array into positional argumentsExpands a hash into keyword arguments
Data Type HandledArrayHash
Introduced InRuby 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:

ruby
def greet(*names)
  names.each { |name| puts "Hello, #{name}!" }
end

greet('Alice', 'Bob', 'Carol')
Output
Hello, Alice! Hello, Bob! Hello, Carol!
↔️

Double Splat Equivalent

This example shows how double splat ** handles keyword arguments as a hash:

ruby
def describe_person(**info)
  info.each { |key, value| puts "#{key}: #{value}" }
end

describe_person(name: 'Alice', age: 30, city: 'NYC')
Output
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

Use * to handle multiple positional arguments as an array.
Use ** to handle multiple keyword arguments as a hash.
Splat expands or collects arrays; double splat expands or collects hashes.
Double splat requires Ruby 2.0 or newer.
Choose splat for ordered arguments and double splat for named arguments.