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

时间:2015-03-12 20:53:51

标签: ruby file io

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

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

这有效,但有一些问题,主要的一个是缓冲区不依赖于线,所以它经常切断当前行,等待输入,并将其余的行放在一个新行上。

有没有更好的方法一次读取几行文件? (奖金问题:是否有更好的方式等待用户?我明显滥用STDIN.gets。)

3 个答案:

答案 0 :(得分:1)

我建议如下。

<强>代码

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:如果truthy(默认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

按Enter键后,屏幕将被清除,并显示以下内容:

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”后,按Enter(或“q”,回车),屏幕保持不变,方法返回。

答案 1 :(得分:0)

您可以使用

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

答案 2 :(得分:0)

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

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,但它确实有用。