简体   繁体   中英

Read next line during file IO in Ruby

I am trying to import a file using ruby and parse it. Is there a way to read the next line once inside the file import? Basically I want to see if a specific line is within x lines of another important line. Like does "x phrase" Come within 10 lines of "y phrase". I don't see a way to do this -- I know its simple with Java. Thanks!

To read lines of a file

lines_array = IO.readlines('testfile')
lines_array.each { |l| #Do your stuff with your line }

Voilà

Ruby Docs on IO

You can also try:

web_contents = "c:\\path\\to\\your\\file.txt"  

File.open(web_contents).each_with_index do |line, i|  
  line.chomp!  
  puts "line #{line}, i #{i}" # Do whatever you want to here  
end  

The .each_with_index method gives you an index, i , which you can use to keep track of where on what line in your file you are. Simple maths can then yield the offset as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM