Ruby Splat Arguments
A method can gather extra arguments into one array. A star before a parameter name does the gathering.
Gathering extra arguments
The star in *scores gathers every argument into one array. The method then holds that array under one name.
def show_scores(*scores)
p scores
end
show_scores(10, 20, 30)
show_scores(5)An empty splat
A call with no arguments still works. The splat simply gathers an empty array.
def count_items(*items)
puts items.length
end
count_items
count_items("pen")A fixed parameter before the splat
A plain parameter before the splat takes the first argument. The splat gathers everything after it.
def greet(greeting, *names)
names.each do |name|
puts "#{greeting}, #{name}"
end
end
greet("Hello", "Ana", "Ben")Spreading an array at a call
A star before an array at a call spreads the items out. Each item lands in its own parameter.
def add_three(a, b, c)
puts a + b + c
end
numbers = [4, 5, 6]
add_three(*numbers)Example
def average(*numbers)
total = 0
numbers.each do |number|
total += number
end
puts total / numbers.length
end
average(10, 20, 30)
average(4, 8)Key points
- A star before a parameter name gathers extra arguments into an array.
- The gathered array holds the values in call order.
- The gathered array can be empty when no extra arguments arrive.
- A fixed parameter can sit before the splat and keeps its own value.
- A star before an array at a call spreads its items back into arguments.
In this example, the splat gathers each call's numbers into one array. The loop adds the numbers into total. The last line divides the total by the count of numbers. The first call averages three numbers and the second call averages two.
Note
The splat gathers arguments of any count, so one method can serve many call shapes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A method starts with def collect(*values). What does values hold after the call collect(7, 8)?