Splats and tuples
The passed arguments become a Tuple in the method’s body:
# elements is Tuple(Int32, Int32, Int32)
sum 1, 2, 3
# elements is Tuple(Int32, Int32, Int32, Float64)
sum 1, 2, 3, 4.5
Arguments past the splat parameter can only be passed as named arguments:
def sum(*elements, initial = 0)
total = initial
elements.each do |value|
total += value
end
total
end
sum 1, 2, 3 # => 6
sum 1, 2, 3, initial: 10 # => 16
Two methods with different required named parameters overload between each other:
def foo(*elements, x)
end
def foo(*elements, y)
2
end
foo x: "something" # => 1
foo y: "something" # => 2
The splat parameter can also be left unnamed, with the meaning “after this, named parameters follow”:
def foo(x, y, *, z)
end
foo 1, 2 # Error, missing argument: z
foo 1, 2, z: 3 # OK
A double splat () captures named arguments that were not matched by other parameters. The type of the parameter is a NamedTuple
:
def foo(x, **other)
# Return the captured named arguments as a NamedTuple
other
end
foo 1, y: 2, z: 3 # => {y: 2, z: 3}
foo y: 2, x: 1, z: 3 # => {y: 2, z: 3}
A NamedTuple
can be splat into a method call by using **
:
def foo(x, y)
x - y
end
tuple = {y: 3, x: 10}
foo **tuple # => 7