我有这个循环:
File.open(path_to_file, "r") do |infile|
infile.each_line do |line|
#do things with line
end
end
我想做什么: 如果当前行为空白" / ^ [\ s] * $ \ n /"跳过接下来的两行并继续阅读。
答案 0 :(得分:0)
对于这种情况,我会做这样的事情:
file = File.open(path_to_file, "r")
while !file.eof?
line = file.gets
if line.match(/^[\s]*$\n/)
2.times{ file.gets if !file.eof? }
else
# do something with line
end
end
答案 1 :(得分:0)
让我们先创建一个测试文件。
str =
" \nNow is \nthe time \n \nfor all \ngood \npeople \n\nto \nsupport\na nasty\n \nperson\n"
puts str
#
# Now is
# the time
#
# for all
# good
# people
#
# to
# support
# a nasty
#
# person
#=> nil
FName = "almost_over"
IO.write(FName, str)
#=> 75
让我们确认文件写得正确。
IO.read(FName) == str
#=> true
我们可以跳过不需要的行,如下所示。
count = 0
IO.foreach(FName) do |line|
if count > 0
count -=1
elsif line.strip.empty?
count = 2
else
puts "My code using the line '#{line.strip}' goes here"
end
end
# My code using the line 'people' goes here
# My code using the line 'a nasty' goes here
#=> nil
由于File是IO(File < IO #=> true
)的子类,您经常会看到使用IO
方法的表达式File
作为接收者(例如, File.read(FName)
)。