class ARGF

ARGF and ARGV

The ARGF object works with the array at global variable ARGV to make $stdin and file streams available in the Ruby program:

Reading

ARGF may read from source streams, which at any particular time are determined by the content of ARGV.

Simplest Case

When the very first ARGF read occurs with an empty ARGV ([]), the source is $stdin:

About the Examples

Many examples here assume the existence of files foo.txt and bar.txt:

$ cat foo.txt
Foo 0
Foo 1
$ cat bar.txt
Bar 0
Bar 1
Bar 2
Bar 3

Sources in ARGV

For any ARGF read except the simplest case (that is, except for the very first ARGF read with an empty ARGV), the sources are found in ARGV.

ARGF assumes that each element in array ARGV is a potential source, and is one of:

Each element that is not one of these should be removed from ARGV before ARGF accesses that source.

In the following example:

Example:

ARGF’s stream access considers the elements of ARGV, left to right:

Because the value at ARGV is an ordinary array, you can manipulate it to control which sources ARGF considers:

Each element in ARGV is removed when its corresponding source is accessed; when all sources have been accessed, the array is empty:

Filepaths in ARGV

The ARGV array may contain filepaths the specify sources for ARGF reading.

This program prints what it reads from files at the paths specified on the command line:

Specifying $stdin in ARGV

To specify stream $stdin in ARGV, us the character '-':

When no character '-' is given, stream $stdin is ignored (exception: see Specifying $stdin in ARGV):

Mixtures and Repetitions in ARGV

For an ARGF reader, ARGV may contain any mixture of filepaths and character '-', including repetitions.

Modifications to ARGV

The running Ruby program may make any modifications to the ARGV array; the current value of ARGV affects ARGF reading.

Empty ARGV

For an empty ARGV, an ARGF read method either returns nil or raises an exception, depending on the specific method.

More Read Methods

As seen above, method ARGF#read reads the content of all sources into a single string. Other ARGF methods provide other ways to access that content; these include:

About Enumerable

ARGF includes module Enumerable. Virtually all methods in Enumerable call method #each in the including class.

Note well: In ARGF, method each returns data from the sources, not from ARGV; therefore, for example, ARGF#entries returns an array of lines from the sources, not an array of the strings from ARGV:

Writing

If inplace mode is in effect, ARGF may write to target streams, which at any particular time are determined by the content of ARGV.

Methods about inplace mode:

Methods for writing: