Win All Your Arguments with Ruby’s Splat Operator

Marc Ferraro
Mar 30 · 4 min read

One of the first things anyone learning Ruby (and many other languages for that matter) understands is that parameters and arguments are the lifeblood of a program. They allow our methods to be dynamic, capable of performing their tasks with abstract data sets rather being hard coded to specific data. As the scope of a your program grows, you may find that your methods need more and more parameters to function. In the simple example below, if we were trying to pass the array below into our method we’d have to access the strings in someway, of which there are many options.

my_fav_colors = ["green", "purple", "blue"]def three_fav_colors(color1, color2, color3)  puts "My three favorite colors are #{color1}, #{color2}, and
#.{color3}."
end

We could possibly create three new variables and then plug those in (likely the least efficient):

fav_color1 = my_fav_colors[0]
fav_color2 = my_fav_colors[1]
fav_color3 = my_fav_colors[2]
three_fav_colors(fav_color1, fav_color2, fav_color3)
=> "My three favorite colors are green, purple, and blue."

We could plug the array indexes in directly, a slightly cleaner approach:

three_fav_colors(my_fav_colors[0], my_fav_colors[1], my_fav_colors[2])
=> "My three favorite colors are green, purple, and blue."

Often in ruby when we are operating with arrays we can enumerate over them. However, here we only want to output a single sentence, and so any enumeration would require clumsy refactoring of the original method.

Enter the splat operator:

three_fav_colors(*my_fav_colors)
=> "My three favorite colors are green, purple, and blue."

By putting * before our array, we told the method to turn each index element into an argument. It’s clean, doesn’t add any extra lines of code, and reads well too. But here’s the best part: the uses of * go way beyond converting an array into arguments.

For example, let’s say our program collected people’s favorite colors, and someone entered five colors. Normally we’d have to find someway to discard the extra data. But with *, we can make our methods smart and ignore any bits of data they don’t need:

my_fav_colors = ["green", "purple", "blue", "yellow", "red"]def three_fav_colors_test(color1, color2, color3)puts "My three favorite colors are #{color1}, #{color2}, and #{color3}."end
three_fav_colors(*my_fav_colors)=> "My three favorite colors are green, purple, and blue."

Ruby would normally complain about passing too many arguments, but by putting * as a fourth argument, our method will accept the first three elements of the array and ignore everything else after. Now we don’t have to write any code reducing our array, and all it took was a single character (two if you count the trusty comma).

The * rabbit hole doesn’t end here however; in fact, this is only the beginning.

Splat parameters are optional, and so if a method using one doesn’t receive any argument, it won’t raise an error:

def meetings(*times)
times.each do |time|
puts "I have a meeting at #{time}."
end
end
meetings
=>nil

We can create methods that take any number of arguments:

def meetings(*times, day)
times.each do |time|
puts "I have a meeting at #{time} on #{day}."
end
end
meetings("3:00", "4:15", "8:00", "Wednesday")
=>"I have a meeting at 3:00 on Wednesday.
"I have a meeting at 4:15 on Wednesday.
"I have a meeting at 8:00 on Wednesday.

The above also shows that the splat can go anywhere in the argument list. We can use it to dynamically set multiple variables at once (thanks to freeCodeCamp for this one):

first, *middle, last = [1,2,3,4,5]first = 1
middle = [2,3,4]
last = 5

It can even be used to convert given objects into an array (source). It works on hashes too:

array = *"pizza"array
=>["pizza"]
array = *{tango: "Argentina", ballet: "France"}
array
=>[[:tango, "Argentina"], [:ballet, "France"]]

The hashes array that we get is pretty funky, but it’s always good to have another tool to use.

Using the splat operator is another one of those ruby techniques that, while it isn’t necessary, opens up a whole new world of shortcuts. It can make your methods smarter, more abstract, and less prone to error. I would go into the doublesplat (**) operator here (which acts very similarly to * only that it works specifically with hashes) but this article does it justice and I’ve kept you here for a while already.

Now go forth and win those arguments. Happy Coding!

a comic style splat! popup
a comic style splat! popup

CodeX

Everything connected with Tech & Code

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store