Variable number of arguments
suggest changeIn a parameter list, the splat operator collects extra arguments into an array. At a call, it expands an array into separate arguments. It is most commonly used to create a method that accepts a variable number of arguments:
# First parameter is the subject and the following parameters are their spouses
def print_spouses(person, *spouses)
spouses.each do |spouse|
puts "#{person} married #{spouse}."
end
end
print_spouses('Elizabeth', 'Conrad', 'Michael', 'Mike', 'Eddie', 'Richard', 'John', 'Larry')
Notice that an array only counts as one argument, so you will need to use the splat operator on the calling side too if you have an array you want to pass:
bonaparte = ['Napoleon','Joséphine','Marie Louise']
print_spouses(*bonaparte)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents