Splat Operator (* and **) (Ruby)

The splat operator * gathers extra arguments into an array (or spreads an array into arguments); the double splat ** does the same for keyword arguments into a hash. They make methods accept variable arguments.

Ruby

A single splat in a method definition, def sum(*nums), collects any number of positional arguments into the array nums. The double splat, def opts(**kw), collects keyword arguments into a hash. This is how Ruby methods accept a variable number of arguments.

At a call site the operators work in reverse, spreading a collection into arguments: method(*array) passes each element as a separate argument, and method(**hash) passes hash pairs as keyword arguments. You can also use * in assignment to destructure: first, *rest = [1,2,3,4].

Splats are everywhere in flexible Ruby APIs and when forwarding arguments (def wrap(*args, **kw); target(*args, **kw); end). They keep method signatures adaptable without overloading.

Syntax

def method(*positional, **keywords)
  ...
end

Examples

Ruby

def total(*nums)
  nums.sum
end

puts total(1, 2, 3, 4)
first, *rest = [10, 20, 30]
puts rest.inspect

Output:

10
[20, 30]

Learn it in a lesson

See also

Back to the Dictionary