1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00
Files
til/ruby/read-the-first-line-from-a-file.md
2021-02-26 11:17:45 -06:00

1.2 KiB

Read The First Line From A File

If I wanted to read the first line from a file with Ruby, I'd probably read the whole thing in, split it by newlines, and grab the first.

File.read('README.md').split(/\n/).first

This is inefficient in that it reads in the entire file. For small files this won't matter, but for larger files it could become a bottleneck.

There is a method of doing this that is just as concise and streams the first part of the file rather than reading it in its entirety. The File.open method takes a block. This means you can pass a symbol-to-proc to it as the block argument.

> File.open('README.md', &:readline).strip
=> "# TIL"
> File.open('README.md', &:gets).strip
=> "# TIL"

Both #readline and #gets will grab the first line including the newline character (hence the #strip). The only difference is that #readline will raise an exception if the file is empty.

These methods both come from the IO module and stream the file rather than slurping the whole thing in.

source