tags:

views:

106

answers:

2

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 run 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"]]
+3  A: 

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"]]
Daniel Vandersluis
Great solution, like it a lot.One trivial comment: in Ruby, comment are introduced with `#`, not `//`
Bryan Ash
@Bryan Oops! I work in PHP all day and wrote this answer at the end of my work day. Nice catch :)
Daniel Vandersluis
A: 

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
Pablo