Show surrounding words when searching for a specific word in a text file (Ruby)

Posted by Ezra on Stack Overflow See other posts from Stack Overflow or by Ezra
Published on 2010-04-19T17:40:45Z Indexed on 2010/04/19 17:43 UTC
Read the original article Hit count: 220

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about ruby

Related posts about text