Reading from input files or STDIN in Ruby using ARGF.

ARGF makes it easy for a Ruby script to read from STDIN, a file specified on the command-line argument or multiple files specified on the command line, all through the same interface.

Recall that ARGV array contains the arguments passed to your Ruby script on the command line.

ARGF assumes that any elements that remain in ARGV represent files. Methods like ARGF.each (accepting a block) and ARGF.readlines (returning an array) operate on the concatenation of all files found in ARGV. If ARGV is empty, then ARGF operates on STDIN instead.

For example, a cat-like program could be implemented in Ruby as:

ARGF.each_line { |line| puts line }

When working with optparse, use the parse! method to strip recognized "flag" parameters from ARGV, leaving only the files you want to operate so that ARGF works just like you want it to. For example:

require 'optparse'

options = { }
opt_parser = do |opt|
  opt.banner = "Usage: #{$0} [OPTIONS]"
  opt.separator  ""
  opt.separator  "OPTIONS"

  opt.on("-h","--heading HEADING","a heading to display.") do |heading|
    options[:heading] = heading

  opt.on("-v","--verbose","be more chatty") do
    options[:verbose] = true

puts options[:heading] unless options[:heading].nil?
ARGF.each_line { |line| puts line }
Tagged ruby, dev and cli.


This page was generated at 4:16 PM on 26 Feb 2018.
Copyright © 1999 - 2018 Rodney Waldhoff.