如何使用 Ruby 一次读取多行文件?

How to read a file several lines at a time with Ruby?

我正在学习 Ruby,我正在尝试以类似于 Linux 终端中的 more 命令的方式读取文件。我这里有一个粗略的版本:

f = File.open("#{file}")
while buffer = f.read(2048) 
    print buffer
    STDIN.gets
end
f.close

这行得通,但有一些问题,主要是缓冲区不依赖于行,所以它经常剪切当前行,等待输入,并将该行的其余部分放在新行上.

有没有更好的方法一次读取多行文件? (奖金问题:还有更好的等待用户的方法吗?我显然在滥用STDIN.gets。)

您可以使用

f.each_line do |buffer|
  print buffer.chomp
  STDIN.gets
end

我想出了自己的解决方案。

f = File.open(file)
f.lines.each_with_index do |line, index|
    if (index+1) % 25 == 0     #Every 25 lines
        STDIN.gets             #Wait for user input
    end
    print line
end
f.close

这让用户可以阅读文件的一部分并继续。我仍然不想使用 STDIN.gets,但它确实有效。

我会提出以下建议。

代码

def more(fname, lines: 23, clear: false)
  f = File.open(fname)
  loop do
    system "clear" if clear
    lines.times { line = f.gets; (puts line) if line }
    puts "\nPress Enter to continue, Q, Enter to quit"   
    case gets.chomp
    when "q", "Q" then return
    else return if f.eof?
    end
  end
end

该方法的操作应该是不言自明的。有两个可选参数:

  • lines:一次显示的行数,默认。
  • clear:如果为真(默认false),则在显示每组行之前清除终端。 system "clear" 适用于 OS X (Mac)。其他操作系统可能需要 system "cls" 或其他东西。

Ruby 将在从方法返回时关闭文件。

例子

首先让我们构建一个测试文件:

FNAME = "t"
str = "It was the best of times,..."
File.write(FNAME, 200.times.map { |i| "#{i}: #{str}"  }.join("\n"))

现在让我们将它打印到屏幕上,一次打印五行,在打印每组行之前清空屏幕:

more FNAME lines: 5, clear: true

屏幕清空,显示如下:

0: It was the best of times,...
1: It was the best of times,...
2: It was the best of times,...
3: It was the best of times,...
4: It was the best of times,...

Press Enter to continue, Q, Enter to quit

回车后清屏,显示如下:

5: It was the best of times,...
6: It was the best of times,...
7: It was the best of times,...
8: It was the best of times,...
9: It was the best of times,...

Press Enter to continue, Q, Enter to quit

按"Q"、回车(或"q"、回车)后,画面不变,方法returns.