← Back to Ruby Course | Chapter 7: Methods | Lesson 4 of 7

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:

  1. Splat Operator (*args)
Syntax
ruby
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)

markup
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)
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
  1. Passing an array directly, as in sum_all(values), which gives one array element; use sum_all(*values).
  2. Placing a required parameter after *numbers and forgetting how Ruby assigns arguments.
  3. Expecting numbers to 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.