3

我需要遍历文件中的每一行。但是,在我读完一行之后,我需要向前看下一行并可能采取一些行动。

如果我使用该peek命令,那么我只会得到文件的第二行。但是,如果我使用next命令移动迭代器,它也会增加.each迭代器。要了解我的意思,请运行下面的 9 行程序并查看输出。如果您将第 7 行注释掉,则将打印整个文件,但peek会出错。如果您不加注释第 7 行,则 peek 有效,但您只能打印一半文件。

我需要一种只增加一次的方法,或者我需要一种不使用.each.

做这个的最好方式是什么?

#!/usr/bin/ruby                       
                                   #1  
curFile = File.open("testcase.rb")     #2  
line_enum = curFile.to_enum            #3  
curFile.each do |line|                 #4  
  puts "=> " + line                    #5  
  puts "  peek > " + line_enum.peek    #6  
  line_enum.next                       #7  
end                                    #8  
4

6 回答 6

1

IO和File包含enumerable,所以each_cons方法可用:

cur_file = File.open("test.csv") do |f| #using a block takes care of closing the file
  f.each_cons(2) do |line1, line2|
    puts "=> #{line1}"
    puts "peek #{line2}" 
  end
end

输出:

=> one
peek two
=> two
peek three
=> three
peek four
于 2013-09-20T20:38:25.900 回答
1

与其peek阅读文件,不如先读取所有行:

 lines = File.readlines('testcase.rb')

这将为您提供所有行的数组。然后,您对如何迭代它们有更大的灵活性。这可能会满足您的需求:

 (lines + [nil]).each_cons(2).each do |line1,line2|
   # do something
 end
于 2013-09-21T16:47:22.440 回答
1

利用each_with_index

curFile = File.readlines("testcase.rb")       

curFile.each_with_index do |line, index|                  
  puts "=> " + line                    
  puts "  peek > " + curFile[index+1]    if index < curFile.count

end   
于 2013-09-20T21:23:19.050 回答
0

作为你想要做的事情的大纲,我会使用类似的东西:

previous_line = nil
File.foreach("testcase.rb") do |li|

  if previous_line

    # Do tests based on "previous_line".
    # If you need to know the current line use "li". 

  end

  previous_line = li
end

# do something to test the "previous_line" by itself 
# if it's possible to have something important there.
于 2013-09-20T22:59:42.667 回答
0

您可以使用while循环而不是#each手动移动光标:

curFile = File.open("peek.txt")
line_enum = curFile.to_enum
while line_enum
  line = line_enum.next
  puts "=> " + line
  puts "  peek > " + line_enum.peek
end

编辑

根据您想要实现的确切目标,您也可以使用#loop而不是while循环。在这种情况下,它会line_enum.peek在文件末尾被调用时跳出循环:

loop do
  line = line_enum.next
  puts "=> " + line
  puts "  peek > " + line_enum.peek
end
于 2013-09-20T19:44:39.457 回答
0

怎样才能扭转问题?与其认为它是向前看,为什么不回头看呢?

#!/usr/bin/ruby                        #1  
curFile = File.open("testcase.rb")     #2  

prev_line = nil
curFile.each do |line|                 #4  
  if prev_line
    # do something to prev_line based on the content of line  
  end

  prev_line = line # turn the current line into prev_line for the next iteration
end                                    #8 
于 2013-09-20T19:14:16.250 回答