Arraying your arguments
The list of parameters passed to an object is, in fact, available as a list. To do this, we use what is called the splat operator – which is just an asterisk (*
).
The splat operator is used to handle methods which have a variable parameter list. Let’s use it to create an add
method that can handle any number of parameters.
We use the inject
method to iterate over arguments
def add(*numbers)
numbers.inject(0) { |sum, number| sum + number }
endputs add(1)
puts add(1, 2)
puts add(1, 2, 3)
puts add(1, 2, 3, 4)
One thought on “splat operator in Ruby”