
10
|
第 1 章
Variadic 方法
定義方法的時候,可以利用 * 運算子讓方法支援數量不固定的引數:
>> def join_with_commas(*words)
words.join(', ')
end
=> nil
>> join_with_commas('one', 'two', 'three')
=> "one, two, three"
定義的方法不能擁有一個以上的長度可變參數,但正常的參數則可以出現在長度可變參
數的任何一側:
>> def join_with_commas(before, *words, after)
before + words.join(', ') + after
end
=> nil
>> join_with_commas('Testing: ', 'one', 'two', 'three', '.')
=> "Testing: one, two, three."
* 運算子也可以在傳送訊息時,用來將每個陣列元素視為獨立的引數:
>> arguments = ['Testing: ', 'one', 'two', 'three', '.']
=> ["Testing: ", "one", "two", "three", "."]
>> join_with_commas(*arguments)
=> "Testing: one, two, three."
最後,* 也可以用在平行指定:
>> before, *words, after = ['Testing: ', ...