tags:

views:

57

answers:

2

Hi, I'm very new to ruby. I'm trying to search for any instance of a word in a text file (not the problem). Then when the word is discovered, it would show the surrounding text (maybe 3-4 words before and after the target word, instead of the whole line), output to a list of instances and continue searching.

Example "The quick brown fox jumped over the lazy dog." Search word = "jumped" Output = "...brown fox jumped over the..."

Any help is appreciated. Thanks! Ezra

def word_exists_in_file
   f = File.open("test.txt")
   f.each do line
      print line
      if line.match /someword/
         return true
      end
   end
   false
end
+1  A: 
def find_word(string, word)
  r1 = /\w+\W/
  r2 = /\W\w+/
  "..." + string.scan(/(#{r1}{0,2}#{word}#{r2}{0,2})/i).join("...") + "..."
end

string = "The quick brown fox jumped over the lazy dog."

find_word(string, "the")
#=> "...The quick brown...jumped over the lazy dog..."

find_word(string, "over")
#=> "...fox jumped over the lazy..."

It's not perfect solution, just the path, so work around it.

fl00r
+1  A: 

Rails has a text helper called excerpt that does exactly this, so if you're trying to do this inside a Rails view:

excerpt('The quick brown fox jumped over the lazy dog',
        'jumped', :radius => 10)
=> "...brown fox jumped over the..."

If you want to use this outside Rails (but you have the Rails gems installed) you can load ActionView:

require "action_view"
ActionView::Base.new.excerpt('The quick brown fox jumped over the lazy dog',
                                 'jumped', :radius => 10)

=> "...brown fox jumped over the..."
andrewmcdonough