ruby - 如何在 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"
我该怎么做呢?
解决方案
那么你可以有几种方法来解决这个问题,最简单的方法是遍历每一行。并尝试像这样检测序列,它应该类似于用于检测序列的状态机:
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
推荐阅读
- android - 在android中使用接口扩展一个具有多个活动的类
- html - 外部 div 在里面修改时搞砸了
- amazon-web-services - 我可以垂直扩展 Amazon 实例吗?
- c# - .NET Core 2.1 基于 .NET 套接字和 Span 的新 HttpClient
. 好像有问题 - regex - 如何用显式“\n”替换单元格中的换行符?
- python - 如何改进解析 lz4 压缩 json 的方法?
- java - Java Stream 有状态 findFirst
- ruby-on-rails - 无法通过多对多关联查询父级 - Rails
- cassandra - 如何在 Cassandra 中可视化原子性?
- java - 使用休眠连接构建独立的 Spring Boot 应用程序