The splat operator in Ruby, Groovy and Perl allows
you to switch between parameters and arrays:
it splits a list in a series of parameters,
or collects a series of parameters to fill an array.
The split mode turns an array into multiple-arguments:
>> duck, cow, pig = *["quack","mooh","oing"] => ["quack","mooh","oing"]
The collect mode turns multiple-arguments in an array:
>> *farm = duck, cow, pig => ["quack","mooh","oing"]
The splat operator can be used in a case statement :
WILD = ['lion','gnu'] TAME = ['cat','cow'] case animal when *WILD "Run" when *TAME "Catch" end
And it can be used to convert a hash into an array:
>> a = *{:a=>1,:b=>2} => [[:a,1],[:b,2]] >> Hash[*a.flatten] => {:a=>1,:b=>2}
If memory serves, you don’t need to splat an array to assign its values to variables, i.e. this should work:
duck, cow, pig = [“quack”,”mooh”,”oing”]
these works the same way without the splat operator:
duck, cow, pig = [“quack”,”mooh”,”oing”]
farm = duck, cow, pig
U have a mistake there in Ruby syntax. The pig should say oink not oing !
I sometimes find the splat operator handy when working with methods:
farm = ["quack","mooh","oing"]
def animals(duck, cow, pig)
puts "duck: #{duck} cow: #{cow} pig:#{pig}"
end
# this fails because array destructuring does
# not work with methods
animals(farm)
# -> in `animals': wrong number of arguments (1 for 3) (ArgumentError)
# but with splat operator it works
animals(*farm)
# -> duck: quack cow: mooh pig:oing
Exactly what I was researching, thanks.
In the last example, you don’t need `.flatten` OR the splat:
Hash[a] # does the same as Hash[*a.flatten]