Reading the first line of a file in Ruby Reading the first line of a file in Ruby ruby ruby

Reading the first line of a file in Ruby


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


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  endend


How to read the first line in a ruby file:

commit_hash = File.open("filename.txt").first

Alternatively you could just do a git-log from inside your application:

commit_hash = `git log -1 --pretty=format:"%H"`

The %H tells the format to print the full commit hash. There are also modules which allow you to access your local git repo from inside a Rails app in a more ruby-ish manner although I have never used them.