Splats have many uses in ruby. When you use a splat in a method call it turns an array into a list of arguments.
def test(*args)
args
end
Consider these examples:
a = [1,2,3]
test(a)
# => [[1, 2, 3]]
test(1,2,3)
# => [1, 2, 3]
test(*a)
# => [1, 2, 3]
In the first example the array is treated as the first argument so the result is an array in an array. While *[1,2,3]
de-structures the array so that we get the desired result.
This makes it extremely useful for calling methods that take a variable number of arguments. yield
works just like any other method in this regard, as using a splat will de-structure the array in args
and call the passed block with a list of arguments.