Ruby the splat * operator
The splat operator (*) in Ruby is a useful tool to handle multiple arguments or elements. It simplifies the handling of variable numbers of arrays, making it versatile.
1. Collecting Multiple Arguments into an Array
When defining a method, the splat operator can be used to gather varying arguments into an array.
def sum_integers(*ints)
ints.inject(0) { |sum, n| sum + n }
end
sum_integers(1, 2, 3, 4)
# => 10
2. Expanding an Array
The splat operator expands an array into individual elements.
It’s useful when passing an array as individual arguments to a method.
numbers = [1, 2, 3, 4]
# Equivalent to puts(1, 2, 3, 4)
puts(*numbers)
# => 1
2
3
4
# same as argument forwarding, case 5
3. Pattern Matching
The splat operator in Ruby 2.7 and later versions is used to match patterns. It can match any number of elements in an array, hash, or object decomposition.
first, *rest = [1, 2, 3, 4]
puts first
# => 1
puts rest
# =>2
3
4
4. Combining Arrays
The splat operator can be used to combine arrays.
array1 = [2, 4]
array2 = [3, 5]
combined = [*array1, *array2]
# => [2, 4, 3, 5]
5. Argument Forwarding
The splat operator can forward arguments to another method.
def greet(name, message)
puts "#{message}, #{name}!"
end
args = ["Rakesh", "Hello"]
# Equivalent to greet("Rakesh", "Hello")
greet(*args)
# => Hello, Rakesh!
6. Ignoring Multiple Return Values
The splat operator can be used in an assignment to ignore multiple return values.
When used in an assignment, it allows for the handling of multiple return values from a function or method.
By placing the splat operator before a variable name, it can be used to capture all remaining arguments in a function call, or to ignore multiple return values.
This is particularly useful when only some of the returned values are needed, or when the number of returned values is variable. In this way, the splat operator provides a flexible and powerful tool for managing data in code.
first, * = [1, 2, 3, 4]
puts first
# => 1
7. Destructuring Arrays
The splat operator can be used to destructure arrays, similar to pattern matching.
it does the exact opposite of Combining Arrays in case 4 above
first, *rest = [1, 2, 3, 4]
puts first
# => 1
puts rest
# => [2, 3, 4]