With UNIX-style text files, it's very simple
f = File.new("/path/to/whatever") num_newlines = 0 while (c = f.getc) != nil num_newlines += 1 if c == "\n" end
What is it. For MS Windows text files, you will need to check the sequence "\ r \ n" instead of "\ n", but this is not much more difficult. For Mac OS Classic text files (unlike Mac OS X), you should check "\ r" instead of "\ n".
So yes, that sounds like C. So what? C is awesome, and Ruby is awesome, because when the C answer is easiest, you can expect your Ruby code to look. Hope yours doesn't have Java already processed.
By the way, please do not even consider any of the answers above that use the IO#read or IO#readlines method, which in turn calls the String method on what has been read. You said you didn’t want to read the entire file in memory and what exactly they do. That's why Donald Knuth recommends that people understand how to program closer to hardware, because if they don’t, they’re “weird code.” Obviously, you do not want to code when you do not need it, but this should be common sense. However, you must learn to recognize cases that you have in order to get close to nuts and bolts such as this one.
And don't try to get more "object oriented" than the situation calls for. This is an awkward trap for beginners who want to look more sophisticated than they really are. You should always be happy when the answer is really simple and not disappointed when there is no difficulty to give you the opportunity to write “impressive” code. However, if you want to look somewhat “object oriented” and don't mind reading the entire line in (i.e. you know that the lines are short enough), you can do this
f = File.new("/path/to/whatever") num_newlines = 0 f.each_line do num_newlines += 1 end
This would be a good compromise, but only if the lines are not too long, in which case it can work even faster than my first Solution.
Richard Ryan Aug 29 '13 at 21:08 2013-08-29 21:08
source share