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

Splat Operator (*args)

In this page:

  1. Splat Operator (*args)

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)

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)
🔒

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.