Splat
The Splat operator (*
) is a useful tool for working with arrays in Ruby.
Not what you're looking for? See the Asterisk page to see the different ways that the asterisk symbol is used.
If a method takes a series of positional arguments and you have an array of values, you can splat the array into the method call.
def sum(a, *rest)
sum_of_rest = rest.any? ? sum(*rest) : 0
a + sum_of_rest
end
values = [1, 1, 2, 3, 5, 8, 13]
# Here is where we splat `values`
sum(*values) #=> 33
The splat operator can also be used to expand an array into another array.
def all_tags(custom_tags=[])
core_tags = ['Ruby', 'Rails', 'SQL']
[*core_tags, *custom_tags].uniq
end
> all_tags
=> ["Ruby", "Rails", "SQL"]
> all_tags([])
=> ["Ruby", "Rails", "SQL"]
> all_tags(nil)
=> ["Ruby", "Rails", "SQL"]
> all_tags('TypeScript')
=> ["Ruby", "Rails", "SQL", "TypeScript"]
> all_tags(["TypeScript", "Go"])
=> ["Ruby", "Rails", "SQL", "TypeScript", "Go"]
Implicit Array Assignment
What we can see in that previous codeblock is an example of Implicit Array Assignment. This is where the splat operator coerces things into an array.
> tag = *'TypeScript'
=> ["TypeScript"]
> tags = 'TypeScript', *['Ruby', 'SQL']
=> ["TypeScript", "Ruby", "SQL"]
Splat a hash
Using the splat operator with a hash turns it into an array of key-value pairs.
> pairs = *{ a: 1, b: 2 }
=> [[:a, 1], [:b, 2]]