Reading the first line of a file in Ruby

Craig Walker picture Craig Walker · Sep 29, 2009 · Viewed 40.9k times · Source

I want to read only the first line of a file using Ruby in the fastest, simplest, most idiomatic way possible. What's the best approach?

(Specifically: I want to read the git commit UUID out of the REVISION file in my latest Capistrano-deployed Rails directory, and then output that to my tag. This will let me see at an http-glance what version is deployed to my server. If there's an entirely different & better way to do this, please let me know.)

Answer

Chuck picture Chuck · Sep 29, 2009

This will read exactly one line and ensure that the file is properly closed immediately after.

strVar = File.open('somefile.txt') {|f| f.readline}
# or, in Ruby 1.8.7 and above: #
strVar = File.open('somefile.txt', &:readline)
puts strVar