2015-11-05 111 views
0

我有一個函數正在使用的參數數組,數組長度可以改變。具有變量數量參數的Ruby調用函數

我想調用數組的參數數量的函數,我怎麼能在ruby中做到這一點。

該數組可以有很多參數,因此某種if/case語句不起作用。

array = ["one","two","tree","four", "five"] 

def callFunction(a) 
    callAnotherFunction(a[0],a[1],a[2],a[3],a[4]) 
end 

我想使用某種循環發送正確數量的參數。 callAnotherFunction函數應該用數組的參數數量來調用。該數組將始終具有正確數量的參數。

+0

是否有一個最大尺寸的陣列?並且這個最大尺寸是否合理? – MCBama

+0

一般來說,我希望它是可擴展的,但我相信它將始終在2和15之間 –

+0

重複? http://stackoverflow.com/q/918449/2988 –

回答

0
def add(*arr) # The * slurps multiple arguments into one array 
    p arr   # => [1, 2, 3] 
    arr.inject(:+) 
end 

p add(1,2,3)  # => 6 

def starts_with_any_of(str, arr) 
    str.start_with?(*arr) # start_with? does not take an array, it needs one or more strings 
         # the * works in reverse here: it splats an array into multiple arguments 
end 

p starts_with_any_of("demonstration", ["pre", "post", "demo"]) # => true 
相關問題