In one of my recent posts someone pointed out that using the splat (*) operator would have made some of the code a bit simpler. I’ve seen the splat operator being used in method definitions (to group remaining arguments), but it turns out there are actually quite a few other uses as well.
This is probably the most common usage of the splat operator – slurping up all remaining arguments. (Yes, slurping – it’s a technical term) C# developers will probably recognize a similarity to the params keyword in .NET. Ruby is a bit more advanced – we can use it anywhere in the method definition.
Ruby is clever enough to match up our arguments as best as possible and pass all additional arguments into the splat parameter. What happens if more than one parameter is using the splat operator?
Ok, so Ruby doesn’t allow us to do something really stupid. Being able to use the splat operator is really just syntactic sugar – it allows us to pass in additional parameters without having to put those parameters into an array.
Multiple Variable Assignment
Ruby already allows us to do multiple variable assignment without the splat operator (it’s one of my favorite features).
However, there are certain scenarios where we need some extra help.
We just lost the last 3 variables! This can be especially useful when you’re working with an array of variable length:
All the examples we’ve looked at so far involve creating an array out of regular variables. The splat operator can also do the opposite – flattening an array:
In some scenarios it can be useful to create arrays out of other variables:
This is a bit neater than having to use (1..10).to_a. I would be a bit careful of using the splat operator in this way, since you can also start to do a few ridiculous things:
It’s obviously important to still keep maintainability in mind when using this operator – just because we can use it doesn’t mean we should.
There are quite a few other scenarios I didn’t cover here – for example, we can use this operator to convert hashes to arrays or call methods with arrays which aren’t really expecting them. While the splat operator can definitely be used effectively in a few niche scenarios it’s very rare to see it being used outside of method definitions. To be honest, I would be careful of using it outside of method definitions, since we don’t want to make the code more complex just to save a few characters here and there.