Ruby - how to read the first n lines from a file to an array

For some reason, I cannot find any tutorial that mentions how to do this ... So, how do I read the first n lines from a file?

I figured it out:

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

but it does not work, and it also does not look very good to me.

Just out of curiosity, I tried things like:

 File.open('file.txt').10.times do |f| 

but that didn't work either.

So, is there an easy way to read only the first n lines without loading the whole file? Thank you very much!

+6
source share
4 answers

Here is a one line solution:

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

I was afraid that he might not close the file as soon as possible (he could close the file only after the garbage collector deleted 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 every time you call the first method on this enumerator, it opens a file, reads as needed, and then close the file. This is good because it means that you can use the line of code above and Ruby will not keep the file open longer than necessary.

+19
source

There are many ways to solve this problem in Ruby. Here is one way:

 File.open('Gemfile') do |f| lines = 10.times.map { f.readline } end 
+5
source
 File.foreach('file.txt').with_index do |line, i| break if i >= 10 puts line end 
+3
source

You can try the following:

 `head -n 10 file`.split 

This is not exactly a β€œpure ruby,” but this is rarely required these days.

-1
source

Source: https://habr.com/ru/post/972109/


All Articles