O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

21.4. Parsing Command-Line Arguments

Problem

You want to make your Ruby script take command-line arguments, the way most Unix utilities and scripts do.

Solution

If you want to treat your command-line arguments as a simple list of strings, you can just iterate over the ARGV array.

Here's a Ruby version of the Unix command cat; it takes a list of files on the command line, opens each one, and prints its contents to standard output:

	#!/usr/bin/ruby -w
	# cat.rb

	ARGV.each { |filename| IO.readlines(filename).each { |line| puts line } }

If you want to treat your command-line arguments as a list of files, and you plan to open each of those files and iterate over them line by line, you can use ARGF instead of eARGV. The following cat implementation is equivalent to the first one.[3]

	#!/usr/bin/ruby -w
	# cat_argf.rb

	ARGF.each { |line| puts line }

If you want to treat certain command-line arguments as switches, or as anything other than a homogenous list of strings, use the OptionParser class in the optparse library. Don't write the argument parsing code yourself; there are too many edge cases to think about.

Discussion

The OptionParser class can parse any command-line arguments you're likely to need, and it includes a lot of Unix know-how that would take a long time to write yourself. All you have to do is define the set of arguments your script accepts, and write code that reacts to the presence of each argument on the command line. Here, I'll use OptionParser to write cat2.rb, a second Ruby version ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required