Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the first line of a file in Ruby

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

like image 214
Craig Walker Avatar asked Sep 29 '09 01:09

Craig Walker


People also ask

How do I read a file line in Ruby?

Use File#readlines to Read Lines of a File in Ruby File#readlines takes a filename to read and returns an array of lines. Newline character \n may be included in each line. We must be cautious when working with a large file, File#readlines will read all lines at once and load them into memory.

How do you read a line by line in Ruby?

The IO instance is the basis for all input and output operations in Ruby. Using this instance, we can read a file and get its contents line by line using the foreach() method. This method takes the name of the file, and then a block which gives us access to each line of the contents of the file.


2 Answers

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 
like image 105
Chuck Avatar answered Sep 22 '22 09:09

Chuck


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 
like image 43
Blake Taylor Avatar answered Sep 21 '22 09:09

Blake Taylor