I usually use following to create a bunch of array elements in Ruby.
Today I noticed following which performs same operation:
My reaction was “Awesome!!!!” .
So, then, one day I took some time to investigate more on this (*) operator.
Following are my findings.
- Generally used in “Method definition with variable no. of parameter”.
- Converting an array into list of arguments in method calling.
In this case, the splat converts the array into method arguments.
- Interesting Array data retrieval:
-
Datatype Coercion : Splat operator can be used to convert interesting datatype coercion.
a) String into Array : Splat can also be used to coerce string values into array.
Note : This will only create array of size 1.
b) Range into Array :
Above is similar behavior as arr = (10..20).to_a
c) Hash into an Array:
Note : Use Hash[*arr.flatten]
to reverse it.