In BlogPost, Ruby

Ruby ARGF For Command Line Applications

About a year ago, I discovered the Ruby ARGF class as a way to help you read files in ruby scripts.

ruby on rails

From the Ruby documentation:

Concatenate file contents

One nifty trick I picked up from this thoughtbot post is that besides concatenating of file contents, you have to shift flags off the ARGV array if you want a Ruby CLI application that accepts options.

To get a better handle on this, let’s look at an example program.

Example CLI – Summing Numbers

For now, let’s focus on ARGF. Here you run the program with:

To give you an idea of the numbers in each file, here they are:



If you run the program, you should see output like:

You would see 6 if I didn’t have the quit word in the numbers2.txt file.

Shifting ARGS off ARGV with OptionParser

The cool thing about OptionParser is that it takes care of shifting arguments off ARGV for you. So you can enter the following at the terminal:

And you will see the following output:


If you’re ever in need of an easy way to read in files from the command line, ARGF could be a handy tool for you. Here is the demo repo I used for this blog post.

Recent Posts