From: 7stud -- Date: 2011-04-28T03:31:17+09:00 Subject: Re: pattern matching and array methods Mfer Dez wrote in post #995245: > I have a text file that is structured like so: > > 1:1 abcdefg > 1:2 abcdefg > 1:3 abcdefg > 1:4 abcdefg > 1:5 abcdefg > > I would like to be able to print out a subset of the file ie: print the > line beginning with 1:2 through the line beginning with 1:4 > If do some work to save the lines in an easily accessible structure, you can make the lookup much easier: lines = [ '1:1 xxxxxx', '1:2 xxxxxx', '1:3 xxxxxx', '1:4 xxxxxx', '1:5 xxxxxx', '2:1 xxxxxx', '2:2 xxxxxx', '2:3 xxxxxx', '2:4 xxxxxx', '2:5 xxxxxx' ] #Create a hash whose non-existent keys #are automatically assigned an empty array: h = Hash.new {|hash, key| hash[key] = []} lines.each do |line| numbers, str = line.split(' ', 2) key, index = numbers.split(':') h[key][index.to_i] = line #If h[key] does not exist it will automatically #be assigned an empty array, which you can then #index into. end target = '2:2 - 2:5' start, stop = target.split(/\s* - \s*/xms) key1, index1 = start.split(':') key2, index2 = stop.split(':') index1, index2 = index1.to_i, index2.to_i p h[key1][index1..index2] --output:-- ["2:2 xxxxxx", "2:3 xxxxxx", "2:4 xxxxxx", "2:5 xxxxxx"] -- Posted via http://www.ruby-forum.com/.