As of ruby 1.9, you can do some pretty odd things with array destructuring and splatting. Putting the star before an object invokes the splat operator, which has a variety of effects. First we’ll start with some very useful examples, then we will poke around the dark corners of ruby’s arrays and the splat operator.

Method Definitions

You can use a splat in a method definition to gather up any remaining arguments:

In the example above, what will get the first argument, then *people will capture however many other arguments you pass into say. A real world example of this can be found in the definition of Delegator#method_missing. A common ruby idiom is to pass a hash in as the last argument to a method. Rails defines an array helper Array#extract_options! to make this idiom easier to handle with variable argument methods, but you can actually get a similar behavior using a splat at the beginning of the argument list:

Now this example only works if you are guaranteed to pass in a hash at the end, but it illustrates that the splat does not need to always come at the end of a method’s parameters. There are also some other odd uses for the splat in method defitions, for instance this is valid:

In this case, the splat converted the array into method arguments. It doesn’t have to be used with methods that take a variable number of arguments though, you can use it in all kinds of other creative ways:

def add(a,b)
a + b
end
pair = [3,7]
add *pair
# 7

Array Destructuring

First of all, lets quickly cover a few things you can do without splatting:

This can be a nice way to make sure that a value is always an array, especially since it will handle objects that do not implement to_a

The splat is a wily beast popping up in odd corners of ruby. I rarely actually use it outside of in method definitions and method calls, but it’s interesting to know that it is available. Have you found any useful idioms that make use of the splat? I would love to hear about them.

Array Destructuring examples where splat operator is not last – syntax error is raised;
Array Coercion `a = *”Hello”` doesn’t make String to Array, but keeps it as a String.

But you can mimic it always like this anyway: a = [“Hello”] – it’s even 2 characters less than .to_a and 1 more when compared to *. Nevertheless i think that it’s more straightforward than using splat in this case.

It doesn’t. It will splat it, but since plus1 takes only one argument then the array will be passed as is. The code will work the same if you lose the * (and if you actually check your code, then you can see that you didn’t use * anywhere in your code examples).