Ruby是一種令人敬畏的語言,有時讓我感到困惑(因爲我不是那麼棒)。而splat參數是造成一些混淆的原因。請賜教。圖示參數之後如何添加參數的方法調用?
考慮下面的方法:
def doSomething(with_this, *and_that)
# ...
end
您可以調用該方法與選項1:
doSomething("With this", "index 0", "index 1", "etc")
或用選項2:
an_array = ["index 0", "index 1", "etc"]
doSomething("With this", *an_array)
但是,如果我的方法,像這樣定義:
def doSomething(with_this, *and_that, and_even_that)
# ...
end
注意這裏是圖示參數後的參數
問題1:有沒有一種方法可添加參數爲and_even_that
除了使用以下方法?
an_array = ["index 0", "index 1", "etc"]
doSomething("With this", *an_array, "With that")
在追求成爲一個出色的Ruby的程序員,我也想知道這些:
額外的問題:
是它不使用一個以上的圖示的最佳實踐方法定義中的參數?
是否最好的做法是在方法定義中爲最後留下splat參數?
預先感謝您。
只是爲了確保我得到了它,在'splat_in_the_middle(*改編,4,5,6) #arg1 == 1,more_args == [2,3,4,5],last_arg == 6' **參數的x個參數** **圖示將與**最後一個** x數字「匹配」來自函數調用的參數? – sargas
完全正確 –
我編輯了我以前的評論。 – sargas