Get the first x lines of a File

Viewed 223

I'm trying to get the first 10 lines from a file into a string and write them to another file.

I've got:

File.open("read_file.txt", "r") do |rf|
  File.open("write.txt", "w") do |wf|
    rf.each_line.with_index do |line, idx|
      break if idx > 9
      wf.puts(line)
    end
  end
end

Is there a more elegant and efficient way to break on a specified number of lines

Ideally something like file.lines(3) : String would be nice but that certainly isn't available.

2 Answers

Here is a more elegant way (but with the same efficiency, I believe)

File.open "read_file.txt" do |io|
  File.write "write.txt", io.each_line.first(10).join("\n")
end

Read the lines of the file with File#read_lines and then take the first 10 lines:

File.read_lines("file")[0..9]
Related