Coercing arrays into parameter list

suggest change

Suppose 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) # wrong number of arguments (1 for 2) (ArgumentError)

Since the array is just one argument, not two, so Ruby throws an exception. 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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents