Advertisement
cd62131

Iterate Search

Feb 21st, 2017
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.12 KB | None | 0 0
  1. #!/usr/bin/ruby
  2. Search = Struct.new :contents, :search, :stop, :direction do
  3.   def iterate_search
  4.     setup
  5.     iterate_search_sub search, 0
  6.   end
  7.   private
  8.   def setup
  9.     @contents_list = contents.lines.to_a
  10.     if direction == :right
  11.       @re = /\S{10}$/
  12.     else
  13.       @contents_list.reverse!
  14.       @re = /\A\S{10}/
  15.     end
  16.   end
  17.   def iterate_search_sub(word, start_line)
  18.     @contents_list.each_with_index do |line, i|
  19.       next if i < start_line
  20.       if line.include? word
  21.         disp word, line
  22.         return if line.include? stop
  23.         iterate_search_sub line[@re], i + 1
  24.         return
  25.       end
  26.     end
  27.     puts "<stop: #{stop}> not found"
  28.   end
  29.   def disp(word, line)
  30.     puts "#{word}\t#{line}"
  31.     puts
  32.   end
  33. end
  34. if $0 == __FILE__
  35.   data = ARGF.read
  36.   Search.new.tap do |s|
  37.     s.contents = data
  38.     s.search = 'ABCDEFGHIJ'
  39.     s.stop = 'D1D2D3D4D5'
  40.     s.direction = :right
  41.     s.iterate_search
  42.   end
  43.   puts '-' * 4
  44.   Search.new.tap do |s|
  45.     s.contents = data
  46.     s.search = 'C9D1D2D3D4'
  47.     s.stop = 'BCDEFGHIJK'
  48.     s.direction = :left
  49.     s.iterate_search
  50.   end
  51. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement