Splat Operator (*args)
The splat lets a method accept any number of inputs and collects them into one list, like a bag that stretches to hold all your groceries. It is written with a star before the name.
In this page:
Syntax
def method_name(*args)
# args is an array of extra arguments
end
method_name(value1, value2, value3)
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
- 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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Passing an array directly, as in
sum_all(values), which gives one array element; usesum_all(*values). - Placing a required parameter after
*numbersand forgetting how Ruby assigns arguments. - Expecting
numbersto be empty and raising an error when no arguments are passed, when it is just[].
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: