Reading the first line of a file in Ruby

Viewed 44707

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

8 Answers

Here's a concise idiomatic way to do it that properly opens the file for reading and closes it afterwards.

File.open('path.txt', &:gets)

If you want an empty file to cause an exception use this instead.

File.open('path.txt', &:readline)

Also, here's a quick & dirty implementation of head that would work for your purposes and in many other instances where you want to read a few more lines.

# Reads a set number of lines from the top.
# Usage: File.head('path.txt')
class File
  def self.head(path, n = 1)
     open(path) do |f|
        lines = []
        n.times do
          line = f.gets || break
          lines << line
        end
        lines
     end
  end
end
Related