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

HUX布斯
TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
Splat運(yùn)算符解壓縮傳遞給函數(shù)的數(shù)組,以便將每個(gè)元素作為單獨(dú)的參數(shù)發(fā)送給函數(shù)。
一個(gè)簡(jiǎn)單的例子:
>> 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 關(guān)注
- 604 瀏覽
添加回答
舉報(bào)
0/150
提交
取消