【问题标题】:Ruby - How to skip 2 lines after reading a blank line from fileRuby - 从文件中读取空行后如何跳过 2 行
【发布时间】:2016-10-25 17:15:39
【问题描述】:

我有这个循环:

File.open(path_to_file, "r") do |infile|
  infile.each_line do |line|
   #do things with line
  end
end

而我想做的事: 如果当前行为空白 "/^[\s]*$\n/" 则跳过接下来的 2 行并从那里继续阅读。

【问题讨论】:

标签: ruby lines skip


【解决方案1】:

对于这种情况,我会这样做:

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

【讨论】:

  • 这里值得注意的是\A\z^$ 更可取,因为后者锚定在行上,而前者是整个字符串。
【解决方案2】:

让我们首先创建一个测试文件。

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 

由于FileIO (File < IO #=> true) 的子类,您经常会看到使用IO 方法的表达式,而File 作为接收者(例如File.read(FName))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多