2010-06-29 132 views
4

我在Ruby中有一個數組(列表):如何在Ruby中做到這一點?

allRows = ["start","one","two","start","three","four","start","five","six","seven","eight","start","nine","ten"] 

我需要運行在這個循環來獲取遇到從「開始」,直到另一個「開始」俱樂部元素的列表,像下面:基於

listOfRows = [["start","one","two"],["start","three","four"],["start","five","six","seven","eight"],["start","nine","ten"]] 

回答

3

Array#split從Rails的:

def group(arr, bookend) 
    arr.inject([[]]) do |results, element| 
    if (bookend == element) 
     results << [] 
    end 
    results.last << element 

    results 
    end.select { |subarray| subarray.first == bookend } # if the first element wasn't "start", skip everything until the first occurence 
end 

allRows = ["start","one","two","start","three","four","start","five","six","seven","eight","start","nine","ten"] 
listOfRows = group(allRows, "start") 
# [["start","one","two"],["start","three","four"],["start","five","six","seven","eight"],["start","nine","ten"]] 
+1

偉大的解決方案,喜歡它很多。 一個簡單的評論:在Ruby中,評論是用'#'引入的,而不是'//' – 2010-06-29 23:31:48

+0

@Bryan哎呀!我整天在PHP工作,並在工作日結束時寫下了這個答案。很好的抓住:) – 2010-06-30 01:31:09

0

如果你能請使用ActiveSupport(例如,內部的Rails):

def groups(arr, delim) 
    dels = arr.select {|e| == delim } 
    objs = arr.split(delim) 

    dels.zip(objs).map {|e,objs| [e] + objs } 
end