Splat Operator (*args)
In this page:
Splat Operator (*args)
A parameter prefixed with *, like *args, collects any number of extra positional arguments into an array inside the method. This lets a method accept a variable number of arguments, similar to variadic functions in other languages. The splat operator can also be used at a call site to expand an array into individual arguments.
Note: The splat operator works both ways: *args collects arguments into an array, and *array expands an array into individual arguments at a call site.
Example: Splat Operator (*args)
def sum_all(*numbers)
numbers.sum
end
puts sum_all(1, 2, 3)
puts sum_all(10, 20, 30, 40)
values = [5, 10, 15]
puts sum_all(*values)
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: