在這個Ruby代碼中,(一元)*操作符是做什么的?給定Ruby代碼line = "first_name=mickey;last_name=mouse;country=usa" record = Hash[*line.split(/=|;/)]我明白第二行的每一件事,除了*操作員-它在做什么,它的文檔在哪里?(你可能猜到,尋找這個案子很難.)
3 回答

HUX布斯
TA貢獻1876條經驗 獲得超6個贊
Splat運算符解壓縮傳遞給函數(shù)的數(shù)組,以便將每個元素作為單獨的參數(shù)發(fā)送給函數(shù)。
一個簡單的例子:
>> def func(a, b, c)
>> puts a, b, c
>> end
=> nil
>> func(1, 2, 3) #we can call func with three parameters
1
2
3
=> nil
>> list = [1, 2, 3]
=> [1, 2, 3]
>> func(list) #We CAN'T call func with an array, even though it has three objects
ArgumentError: wrong number of arguments (1 for 3)
from (irb):12:in 'func'
from (irb):12
>> func(*list) #But we CAN call func with an unpacked array.
1
2
3
=> nil
就這樣!
- 3 回答
- 0 關注
- 597 瀏覽
添加回答
舉報
0/150
提交
取消