1

我想读入一个文件并显示它有多大。.count 的行为就像 .count!并更改我的输入文件缓冲区的大小。所以现在 logfile.each 不会迭代。这是怎么回事?

logfile = open(input_fspec) 
puts "logfile size: #{logfile.count} lines"
4

2 回答 2

3

count will read all the lines from the input in order to do the counting. If you want to read the lines again (e.g. using readline or each) then you will need to call logfile.rewind to move back to the start of the file.

In fact, what count is actually returning is the number of lines that have not been read yet. For example, if you had already read through the file and called count afterwards then it would return 0.

于 2012-05-17T15:39:31.923 回答
1

You could do this instead before you even open it:

File.size("input_fspec")
于 2012-05-17T15:38:57.800 回答