From 65a0fe0a9d99facbca8a0596bb7fdb5cea55cf68 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 26 Feb 2021 11:17:45 -0600 Subject: [PATCH] Add Read The First Line From A File as a Ruby til --- README.md | 3 ++- ruby/read-the-first-line-from-a-file.md | 33 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 ruby/read-the-first-line-from-a-file.md diff --git a/README.md b/README.md index 98be223..c2737eb 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1062 TILs and counting..._ +_1063 TILs and counting..._ --- @@ -884,6 +884,7 @@ _1062 TILs and counting..._ - [Percent Notation](ruby/percent-notation.md) - [Question Mark Operator](ruby/question-mark-operator.md) - [Rake Only Lists Tasks With Descriptions](ruby/rake-only-lists-tasks-with-descriptions.md) +- [Read The First Line From A File](ruby/read-the-first-line-from-a-file.md) - [Rendering ERB](ruby/rendering-erb.md) - [Replace The Current Process With An External Command](ruby/replace-the-current-process-with-an-external-command.md) - [Require Entire Gemfile In Pry Session](ruby/require-entire-gemfile-in-pry-session.md) diff --git a/ruby/read-the-first-line-from-a-file.md b/ruby/read-the-first-line-from-a-file.md new file mode 100644 index 0000000..bb6843b --- /dev/null +++ b/ruby/read-the-first-line-from-a-file.md @@ -0,0 +1,33 @@ +# 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. + +```ruby +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. + +```ruby +> 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](https://blog.appsignal.com/2018/07/10/ruby-magic-slurping-and-streaming-files.html). + +[source](https://stackoverflow.com/questions/1490138/reading-the-first-line-of-a-file-in-ruby)