Coercing arrays into parameter list
suggest changeSuppose you had an array:
pair = ['Jack','Jill']
And a method that takes two arguments:
def print_pair (a, b)
puts "#{a} and #{b} are a good couple!"
end
You might think you could just pass the array:
print_pair(pair) # ArgumentError: wrong number of arguments (given 1, expected 2)
The array is one argument, not two, so Ruby raises. You could pull out each element individually:
print_pair(pair[0], pair[1])
Or you can use the splat operator to save yourself some effort:
print_pair(*pair)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents