1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Read The First Line From A File as a Ruby til

This commit is contained in:
jbranchaud
2021-02-26 11:17:45 -06:00
parent b3f5614ea8
commit 65a0fe0a9d
2 changed files with 35 additions and 1 deletions

View File

@@ -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)

View File

@@ -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)