0
0
RubyConceptBeginner · 3 min read

Double Splat Operator in Ruby: What It Is and How to Use It

The double splat operator (**) in Ruby is used to capture or pass keyword arguments as a hash. It allows methods to accept any number of named arguments or forward them easily, making code flexible and clean.
⚙️

How It Works

The double splat operator ** in Ruby works like a magic bag that collects all keyword arguments into a single hash. Imagine you have a method that can take many named options, but you don't know in advance which ones. Using ** lets you gather all those named options neatly into one place.

When calling a method, you can also use ** to unpack a hash into keyword arguments. It's like spreading out a set of labeled boxes so the method can receive each label and value as separate named inputs. This makes passing around flexible options easy and clear.

💻

Example

This example shows how to use the double splat operator to accept any keyword arguments and then print them:

ruby
def greet(**options)
  options.each do |key, value|
    puts "#{key}: #{value}"
  end
end

greet(name: "Alice", age: 30, city: "Paris")
Output
name: Alice age: 30 city: Paris
🎯

When to Use

Use the double splat operator when you want your method to accept flexible keyword arguments without listing them all. This is helpful for configuration settings, options hashes, or forwarding arguments to other methods.

For example, if you build a method that customizes a user profile, you might not know all possible options ahead of time. Using ** lets you handle any extra named arguments gracefully.

Key Points

  • Collects keyword arguments: ** gathers all named arguments into a hash.
  • Unpacks hashes: ** can also spread a hash into keyword arguments when calling methods.
  • Improves flexibility: Makes methods accept or forward any keyword options easily.
  • Requires Ruby 2.0+: The double splat operator was introduced in Ruby 2.0.

Key Takeaways

The double splat operator (**) collects keyword arguments into a hash.
It can also unpack a hash into keyword arguments when calling methods.
Use it to write flexible methods that accept or forward named options.
It helps keep code clean when dealing with many or unknown keyword arguments.