首页 > 解决方案 > 如何在 ruby​​ 中一次访问多行

问题描述

我正在编写一个程序来解析基本文本文件,并将其中的某些行与测试结果进行比较。我正在使用特定的词来查找应该与测试结果进行比较的行,然后根据该行是否与结果匹配(它们应该完全相同)来通过或失败结果。我使用以下一般格式:

File.open(file).each do |line|
  if line include? "Revision"
    if line==result
     puts "Correct"
    else
     puts "Fail"

大多数情况只是一行,所以这很容易。但对于少数情况,我的结果是 4 行,而不仅仅是 1 行。所以,一旦我找到我需要的行,我需要检查结果是否等于感兴趣的行加上后面的 3 行。这是正在读取的文件中信息的格式,以及测试结果的外观:

Product Serial Number: 12058-2865
Product Part Number: 3456
Product Type: H-Type
Product Version: 2.07

一旦找到感兴趣的线,我只需要将感兴趣的线加上接下来的三行与整个结果进行比较。

if line include? "Product Serial Number"
  #if (#this line and the next 3) == result
   puts Correct
  else
   puts "Fail"

我该怎么做呢?

标签: rubyfile-iofileparsing

解决方案


那么你可以有几种方法来解决这个问题,最简单的方法是遍历每一行。并尝试像这样检测序列,它应该类似于用于检测序列的状态机:

step = 0
File.open('sample-file.txt').each do |line|
  if /^Product Serial Number.*/.match? line
    puts(step = 1)
  elsif /^Product Part Number.*/.match?(line)  && step == 1
    puts(step = 2)
  elsif /^Product Type.*/.match?(line) && step == 2
    puts(step = 3)
  elsif /^Product Version.*/.match?(line) && step == 3
    puts 'correct'
    puts(step = 0)
  else
    puts(step = 0)
  end
end

结果:

ruby read_file.rb
1
2
3
correct
0
0
1
0
0
0
0
0
0
1
2
3
correct
0
0

这个示例文件:

Product Serial Number: 12058-2865
Product Part Number: 3456
Product Type: H-Type
Product Version: 2.07
no good line
Product Serial Number: 12058-2865
BAD Part Number: 3456
Product Type: H-Type
Product Version: 2.07
no good line
no good line
no good line
Product Serial Number: 12058-2865
Product Part Number: 3456
Product Type: H-Type
Product Version: 2.07
no good line

推荐阅读