简体   繁体   English

在Ruby中的文件IO期间读取下一行

[英]Read next line during file IO in Ruby

I am trying to import a file using ruby and parse it. 我正在尝试使用ruby导入文件并进行解析。 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. 基本上,我想查看特定行是否在另一重要行的x行内。 Like does "x phrase" Come within 10 lines of "y phrase". 就像“ x短语”一样,在“ y短语”的10行之内。 I don't see a way to do this -- I know its simple with Java. 我没有办法做到这一点-我知道使用Java很简单。 Thanks! 谢谢!

To read lines of a file 读取文件行

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

Voilà Voilà

Ruby Docs on IO IO上的Ruby文档

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. .each_with_index方法为您提供一个索引i ,您可以使用它来跟踪文件所在行的位置。 Simple maths can then yield the offset as required. 然后,简单的数学运算就可以根据需要得出偏移量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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