Ruby: Splat
Splat! -> Collecting Remaining Arguments
The Ruby splat is represented by an asterisk (*) and marks a parameter that collects many arguments taken by a method. It is useful when a method will be passed several parameters or blocks and it would not be especially fun to write them all out. It is also great if you will be continually creating more blocks for the method to process. Here is a simple example:
So here you can see that *foods
uses the splat operator and therefore stands in for Zebra
, Antelope
and Buffalo
, while animal
stands only for the first argument that the predator
method takes, Lion
. The splat helps us to pass the method several arguments without having to put these arguments inside an array. You can see that the splat treats the remaining arguments as though they really are arrays, and for this reason splats can also be used for…
…Creating Arrays
The splat operator can be used as a shortcut to making a range into an array, instead of using .to_a
, like so:
Flattening Arrays
Splat operators also allow us to flatten arrays. This can be done in the following way:
Here the splat is telling the second_array to access and insert every element within first_array.
Coverting Hashes to Arrays
Another use for the splat is to convert a Hash into an Array. This is simply done like so:
Beware
By far the best use of a splat is when we want to collect remaining arguments to be passed to a method. This will be very helpful in many situations. However the other uses shown here should be used with caution, because while *
can essentially stand in for .to_a
, but simply using .to_a
instead has the safety of only achieving one goal and so does not make your code any more complex or confused when adding extra functionality.