0
0
RubyConceptBeginner · 3 min read

What is Splat Operator in Ruby: Simple Explanation and Examples

The splat operator in Ruby is *, which lets you work with variable numbers of arguments or convert arrays into a list of arguments. It helps you collect multiple values into one array or expand an array into separate arguments.
⚙️

How It Works

The splat operator * in Ruby acts like a magic helper that can gather many values into one container or spread a container's contents out. Imagine you have a bag of apples (an array), and you want to either carry them all together or hand them out one by one. The splat operator lets you do both.

When used in method definitions, it collects all extra arguments into an array. When used in method calls, it takes an array and spreads its items as individual arguments. This makes your code flexible and neat, especially when you don't know how many inputs you'll get.

💻

Example

This example shows how the splat operator collects extra arguments into an array and how it expands an array into separate arguments when calling a method.

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

people = ["Alice", "Bob", "Charlie"]

greet(*people)
Output
Hello, Alice! Hello, Bob! Hello, Charlie!
🎯

When to Use

Use the splat operator when you want your methods to accept any number of arguments without fixing the count. This is useful for functions like greeting many people, summing numbers, or handling options.

Also, use it to pass an array's elements as separate arguments to another method, making your code cleaner and avoiding manual unpacking.

Real-world cases include logging messages with varying details, combining lists, or forwarding arguments in wrapper methods.

Key Points

  • The splat operator is * in Ruby.
  • It collects multiple arguments into an array in method definitions.
  • It expands arrays into individual arguments in method calls.
  • It makes methods flexible to handle varying numbers of inputs.
  • It helps write cleaner and more readable code.

Key Takeaways

The splat operator * collects or expands arguments in Ruby methods.
Use it to handle variable numbers of arguments easily and cleanly.
It converts arrays to argument lists and vice versa for flexible code.
It simplifies method calls and definitions when argument counts vary.