From: Josh Cheek Date: 2011-01-15T20:55:11+09:00 Subject: Re: Retrieving and copying element from array --00163631005ff7dfa60499e13876 Content-Type: text/plain; charset=ISO-8859-1 On Fri, Jan 14, 2011 at 3:03 PM, Simon Harrison wrote: > Josh: Thanks for the reply and link to your github example. The thing > is, this data is coming from a text file. An export from an MS Access > database. I wouldn't choose to save in that format. > > -- > Posted via http://www.ruby-forum.com/. > > Hi, Simon. Okay, well, if we assume that all data will be nested below a category, and a category is denoted by "category: ", and there isn't leading or trailing whitespace, and all data under the category is given on one line, then this should work with your data format. # goal format for the data, as given in the original post goal = [ ["cat1", "item1", "item2", "item3"], ["cat2", "item1"], ["cat3", "item1", "item2", "item3", "item4"] ] categories = Array.new File.foreach "test.txt" do |line| if line =~ /^category:/ categories << [ line.sub(/^category: /,'').chomp ] else categories.last << line.strip end end goal == categories # => true puts File.read('test.txt') # >> category: cat1 # >> item1 # >> item2 # >> item3 # >> category: cat2 # >> item1 # >> category: cat3 # >> item1 # >> item2 # >> item3 # >> item4 --00163631005ff7dfa60499e13876--