But what if you want to pass in a variable number of arguments, or
want to capture multiple arguments into a single parameter?
Placing an asterisk before the name of the parameter after the
``normal'' parameters does just that.
def varargs(arg1, *rest)
|
"Got #{arg1} and #{rest.join(', ')}"
|
end
|
|
varargs("one")
|
� |
"Got one and "
|
varargs("one", "two")
|
� |
"Got one and two"
|
varargs "one", "two", "three"
|
� |
"Got one and two, three"
|
In this example, the first argument is assigned to the first method
parameter as usual. However, the next parameter is prefixed with an
asterisk, so all the remaining arguments are bundled into a new
Array
, which is then assigned to that parameter.