Processes Have Arguments

Every process has access to a special array called ARGV. Other programming languages may implement it slightly differently, but every one has something called ‘argv’.

argv is a short form for ‘argument vector’. In other words: a vector, or array, of arguments. It holds the arguments that were passed in to the current process on the command line. Here’s an example of inspecting ARGV and passing in some simple options.

$ cat argv.rb
p ARGV
$ ruby argv.rb foo bar -va
["foo", "bar", "-va"]

It’s an Array!

Unlike the previous chapter, where we learned that ENV isn’t a Hash, ARGV is simply an Array. You can add elements to it, remove elements from it, change the elements it contains, whatever you like. But if it simply represents the arguments passed in on the command line why would you need to change anything?

Some libraries will read from ARGV to parse command line options, for example. You can programmatically change ARGV before they have a chance to see it in order to modify the options at runtime.

In the Real World

The most common use case for ARGV is probably for accepting filenames into a program. It’s very common to write a program that takes one or more filenames as input on the command line and does something useful with them.

The other common use case, as mentioned, is for parsing command line input. There are many Ruby libraries for dealing with command line input. One called optparse is available as part of the standard library.

But now that you know how ARGV works you can skip that extra overhead for simple command line options and do it by hand. If you just want to support a few flags you can implement them directly as array operations.

# did the user request help?
ARGV.include?('--help')
# get the value of the -c option
ARGV.include?('-c') && ARGV[ARGV.index('-c') + 1]