Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.open('file.txt') and count <= 3 do |f|
  ...
    count += 1
  end
end

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.open('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!

like image 208
Chris Illusion Avatar asked Jul 11 '14 23:07

Chris Illusion


2 Answers

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.

like image 142
David Grayson Avatar answered Nov 15 '22 18:11

David Grayson


There are many ways you can approach this problem in Ruby. Here's one way:

File.open('Gemfile') do |f|
  lines = 10.times.map { f.readline }
end
like image 27
infused Avatar answered Nov 15 '22 18:11

infused