How to do this in Ruby?
I have an array(list?) in ruby:
allRows = ["start","one","two","start","three","four","start","five","six","seven","eight","start","nine","ten"]
I need to ru开发者_C百科n a loop on this to get a list that clubs elements from "start" till another "start" is encountered, like the following:
listOfRows = [["start","one","two"],["start","three","four"],["start","five","six","seven","eight"],["start","nine","ten"]]
Based on Array#split
from 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"]]
If you can use ActiveSupport (for example, inside Rails):
def groups(arr, delim)
dels = arr.select {|e| == delim }
objs = arr.split(delim)
dels.zip(objs).map {|e,objs| [e] + objs }
end
精彩评论