Get line count before looping over data in ruby
I need to get the total number of lines that an IO object contains before looping through each line in the IO object. How can I do this 开发者_如何学Pythonin ruby?
You can't really, unless you want to shell out to wc
and parse the result of that - otherwise you'll need to do two passes - one to get the line numbers, and another to do your actual work.
(assuming we're talking about a File
IO
instance - neither of those approaches work for network sockets etc)
in rails (the only difference is how I generate the file object instance)
file = File.open(File.join(Rails.root, 'lib', 'assets', 'file.json'))
linecount = file.readlines.size
io.lines.count
would give you the number of lines.
io.lines.each_with_index {|line, index|}
would give you each line and which line number it is (starting at 0).
But I don't know if it's possible to count the number of lines without reading a file.
You may want to read a file, and then use io.rewind
to read it again.
If your file is not humongous, slurp it into memory(array) and count the the number of items( ie lines).
精彩评论