Chris Illusion Chris Illusion - 1 year ago 122
Ruby Question

Ruby - how to read first n lines from file into array

For some reason, I can't find any tutorial mentioning how to do this...
So, how do I read the first n lines from a file?

I've come up with:

while'file.txt') and count <= 3 do |f|
count += 1

but it is not working and it also doesn't look very nice to me.

Just out of curiosity, I've tried things like:'file.txt').10.times do |f|

but that didn't really work either.

So, is there a simple way to read just the first n lines without having to load the whole file?
Thank you very much!

Answer Source

Here is a one-line solution:

lines = File.foreach('file.txt').first(10)

I was worried that it might not close the file in a prompt manner (it might only close the file after the garbage collector deletes the Enumerator returned by File.foreach). However, I used strace and I found out that if you call File.foreach without a block, it returns an enumerator, and each time you call the first method on that enumerator it will open up the file, read as much as it needs, and then close the file. That's nice, because it means you can use the line of code above and Ruby will not keep the file open any longer than it needs to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download