OxAX mentioned one good use of the * prefix operator - to collect arguments and this is what it does in your example.
def lots_of_args *args
p args
end
lots_of_args 1,2,3 # => [1, 2, 3]
first, *rest = 1, 2, 3, 4
first # => 1
rest # => [2, 3, 4]
We can even apply it outside of method definitions.
However, it's important to note that there's another good use for it:
def add_three_nums a, b, c
a + b + c
end
add_three_nums *[1,2,3] # => 6
# same as calling "add_three_nums 1,2,3"
Essentially, the *
operator expands a method argument that's an array into a list of arguments.
There's even a third use case:
first, *rest = [1, 2, 3, 4]
first # => 1
rest # => [2, 3, 4]
This third case is somewhat similar to the first. However, notice that we get the values of first
and rest
from an array, not from a list of values.