charudatta
charudatta

Reputation: 409

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 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"]]

Upvotes: 4

Views: 157

Answers (2)

Pablo
Pablo

Reputation: 1

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

Upvotes: 0

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94163

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"]]

Upvotes: 3

Related Questions