dcvii
dcvii

Reputation: 53

Ruby .count operation truncates input file

I want to read a file in and show how large it is. .count is acting like .count! and changing the size of my input file buffer. so now logfile.each doesn't iterate. What's going on?

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

Upvotes: 1

Views: 90

Answers (2)

mikej
mikej

Reputation: 66293

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.

Upvotes: 3

vlasits
vlasits

Reputation: 2235

You could do this instead before you even open it:

File.size("input_fspec")

Upvotes: 1

Related Questions