Ruby Language Splat operator (*) Coercing arrays into parameter list

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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)


Got any Ruby Language Question?