liveBook · Manning

Splat operator

As explained in The Well-Grounded Rubyist, Fourth Edition

The splat operator is Ruby's * syntax for expanding an array or array-convertible object into a list of elements or arguments.

Ruby’s splat operator, written *, unwraps an array or an array-convertible object into a bare list of elements. In a method call, it expands an array into separate arguments: names = ["David", "Black"]; combine_names(*names) passes two arguments rather than one array. section 7.4.2

The distinction is easiest to see when constructing arrays. [*array] copies the array’s elements into a new array, while [array] creates a nested array containing array as one item. The star therefore has an unarraying, or bracket-removing, effect. section 7.4.2

The same syntax also appears in parameter lists:

  • A starred parameter such as *c collects remaining arguments into an array. section 2.4.2
  • Required parameters before and after the splat receive values before the catch-all parameter does. section 2.4.2
  • When no arguments remain, the catch-all parameter becomes an empty array; too few required arguments still raise an ArgumentError. section 2.4.2

Mixed required and catch-all parameters

def mixed_args(a,b,*c,d)\n puts "Arguments:"\n p a,b,c,d\nend\nmixed_args(1,2,3,4,5)\n# 1\n# 2\n# [3, 4]\n# 5\n\nRuby assigns the required arguments at both ends first, then places the middle values in c. section 2.4.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains bare lists, array conversion through to_a, parameter priority, empty catches, and insufficient-argument errors.
Examples
Uses array reconstruction, name passing, Struct conversion, and methods mixing required, optional, and catch-all parameters.
What it assumes
Assumes familiarity with arrays, methods, arguments, and parameters while explaining array conversion and bare-list behavior.
What you can do after
Apply it in Ruby method calls and definitions to expand arrays or capture remaining arguments predictably.
How it connects
Connects arrays, method arguments, method parameters, Struct, Enumerable, and to_a.

Also explained in

Compare how 2 books explain splat operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.