Splat Operator in Ruby
Ruby splat operator (*variable) is used to convert an array of elements into an argument list.
Example Usecase
Date is passed by the user in the format : 2013/04/03 (YYYY/MM/DD), and you convert this date string to an array of integers using split and map.
|
|
which would give the output [2013,04,03]
.
Now to convert this into a Time object, we need to supply this array as arguments into the Time.new.
The format of which is
|
|
we can’t put the above array as such to Time.new.We need to change the array to arguments such that the first element would be marked as year, second one the month, and third one the day. Here is where we use, the splat operator.
|
|
Ruby splat can be used to accept inputs to a method as an array
|
|
=>
|
|
The rest of the inputs will get stored into the bar as an array. So, in cases where we don’t know how many inputs we are expecting ,we can use this operator.
Convert Hash to array and array to Hash
Splat operator can be used to convert array to hash, and hash to array.
|
|
=>
|
|
|
|
=>
|
|
Double splat in ruby 2.0 +
I haven’t explored the full possibilities of this operator. The double spat can be used to store the hash that is passed into a method.
|
|
=>
|
|
Example with all of them together
|
|
=>
|
|