質問

Possible Duplicate:
What is the * operator doing to this string in Ruby

I ran across the following code when looking for an easy way to convert an array to a hash (similar to .Net's ToDictionary method on IEnumerable... I wanted to be able to arbitrarily set the key and the value).

a = [ 1, 2, 3, 4, 5, 6 ]
h = Hash[ *a.collect { |v| [ v, v ] }.flatten ]

My question is, what does the asterisk before a.collect do?

By the way, the code comes from http://justatheory.com/computers/programming/ruby/array_to_hash_one_liner.html

役に立ちましたか?

解決

It's the splat-operator if you want to google it. It does transform an array into a list (so you can use an array as arguments to a method). It also does the opposite: it can 'slurp' a list into an array.

require 'date'
*date_stuff = 2012,2,29 # slurp
p date_stuff #=> [2012, 2, 29]
Date.new(*date_stuff) # regurgitate
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top