Learn how to parse command line options in your Ruby scripts with the OptionParser class, available in the Ruby standard library.
Defining the options
Start by requiring optparse, and initializing a new OptionParser object with a block that defines which options the parser accepts. For example:
require 'optparse'
option_parser = OptionParser.new do |opts|
opts.on '-i', '--include', 'Include protocol headers'
opts.on '-v', '--[no-]verbose', 'Make the operation more talkative'
opts.on '-m', '--message=MSG', 'Use the given message'
end
OptionParser supports single character "short" options (-i), multi-character "long" options (--include), multiple single character options specified together (-iv), negative forms of boolean options (--no-verbose), and both styles of options with arguments (either --message=Hey or --message Hello).
You can also pass a block to OptionParser#on that will be executed when the option is parsed—useful if you want any side effects to execute immediately.
Parsing command line options
With the options defined you can then use the OptionParser#parse! method to parse command line arguments into an options hash, like this:
options = {}
option_parser.parse!(into: options)
The ARGV
array will be modified destructively, and any remaining arguments that aren’t options will be left in the array. For testing you can pass in different arrays of strings.
Argument type coercion
Type coercion is supported by specifying the expected class of the argument, like this:
option_parser = OptionParser.new do |opts|
opts.on '-p', '--port=PORT', Integer, 'Define the port'
opts.on '-n', '--names=NAMES', Array, 'Define the list of names'
end
With this example a port argument will be coerced into an integer, and a comma separated names argument will be coerced into an array of strings.
Some of the type coercions need an extra require (Date, Time, and URI for example), and some more specific numeric coercions are defined as classes within the OptionParser namespace (OptionParser::DecimalInteger for example).
Displaying a help summary
OptionParser can be used to automatically generate a "help" or "usage" summary using the given argument descriptions. Simply puts the OptionParser object, like this:
puts option_parser
You can use OptionParser#banner= to change the banner message (the first line of the help summary), and OptionParser#program_name= to change the program name (the name of your script used inside the banner message).