Tutorial¶ ↑
Why OptionParser?¶ ↑
When a Ruby program executes, it captures its command-line arguments and options into variable ARGV. This simple program just prints its ARGV:
p ARGV
Execution, with arguments and options:
$ ruby argv.rb foo --bar --baz bat bam ["foo", "--bar", "--baz", "bat", "bam"]
The executing program is responsible for parsing and handling the command-line options.
OptionParser offers methods for parsing and handling those options.
With OptionParser, you can define options so that for each option:
-
The code that defines the option and code that handles that option are in the same place.
-
The option may take no argument, a required argument, or an optional argument.
-
The argument may be automatically converted to a specified class.
-
The argument may be restricted to specified forms.
-
The argument may be restricted to specified values.
The class also has method help, which displays automatically-generated help text.
Contents¶ ↑
To Begin With¶ ↑
To use OptionParser:
-
Require the
OptionParsercode. -
Create an
OptionParserobject.