D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
opt
/
alt
/
ruby34
/
share
/
ri
/
system
/
optparse
/
Filename :
page-tutorial_rdoc.ri
back
Copy
U:RDoc::TopLevel[ i I"optparse/tutorial.rdoc:ETcRDoc::Parser::Simpleo:RDoc::Markup::Document:@parts[|S:RDoc::Markup::Heading: leveli: textI" Tutorial;To:RDoc::Markup::BlankLine S; ; i;I"Why +OptionParser+?;T@ o:RDoc::Markup::Paragraph;[I"JWhen a Ruby program executes, it captures its command-line arguments ;TI"%and options into variable ARGV. ;TI"0This simple program just prints its +ARGV+:;T@ o:RDoc::Markup::Verbatim;[I"p ARGV ;T:@format0o; ;[I"+Execution, with arguments and options:;T@ o;;[I",$ ruby argv.rb foo --bar --baz bat bam ;TI"-["foo", "--bar", "--baz", "bat", "bam"] ;T;0o; ;[I"CThe executing program is responsible for parsing and handling ;TI"the command-line options.;T@ o; ;[I"HOptionParser offers methods for parsing and handling those options.;T@ o; ;[I"IWith +OptionParser+, you can define options so that for each option:;T@ o:RDoc::Markup::List: @type:BULLET:@items[ o:RDoc::Markup::ListItem:@label0;[o; ;[I"HThe code that defines the option and code that handles that option ;TI"are in the same place.;To;;0;[o; ;[I"SThe option may take no argument, a required argument, or an optional argument.;To;;0;[o; ;[I"FThe argument may be automatically converted to a specified class.;To;;0;[o; ;[I"9The argument may be restricted to specified _forms_.;To;;0;[o; ;[I":The argument may be restricted to specified _values_.;T@ o; ;[I"WThe class also has method #help, which displays automatically-generated help text.;T@ S; ; i;I" Contents;T@ o;;;;[o;;0;[o; ;[I"*{To Begin With}[#label-To+Begin+With];To;;0;[o; ;[I"0{Defining Options}[#label-Defining+Options];To;;0;[o; ;[I"({Option Names}[#label-Option+Names];To;;;;[ o;;0;[o; ;[I"4{Short Option Names}[#label-Short+Option+Names];To;;0;[o; ;[I"2{Long Option Names}[#label-Long+Option+Names];To;;0;[o; ;[I"6{Mixing Option Names}[#label-Mixing+Option+Names];To;;0;[o; ;[I"B{Option Name Abbreviations}[#label-Option+Name+Abbreviations];To;;0;[o; ;[I"0{Option Arguments}[#label-Option+Arguments];To;;;;[ o;;0;[o; ;[I">{Option with No Argument}[#label-Option+with+No+Argument];To;;0;[o; ;[I"J{Option with Required Argument}[#label-Option+with+Required+Argument];To;;0;[o; ;[I"J{Option with Optional Argument}[#label-Option+with+Optional+Argument];To;;0;[o; ;[I"<{Argument Abbreviations}[#label-Argument+Abbreviations];To;;0;[o; ;[I".{Argument Values}[#label-Argument+Values];To;;;;[o;;0;[o; ;[I"@{Explicit Argument Values}[#label-Explicit+Argument+Values];To;;;;[o;;0;[o; ;[I"@{Explicit Values in Array}[#label-Explicit+Values+in+Array];To;;0;[o; ;[I">{Explicit Values in Hash}[#label-Explicit+Values+in+Hash];To;;0;[o; ;[I">{Argument Value Patterns}[#label-Argument+Value+Patterns];To;;0;[o; ;[I":{Keyword Argument into}[#label-Keyword+Argument+into];To;;;;[o;;0;[o; ;[I"4{Collecting Options}[#label-Collecting+Options];To;;0;[o; ;[I"H{Checking for Missing Options}[#label-Checking+for+Missing+Options];To;;0;[o; ;[I"D{Default Values for Options}[#label-Default+Values+for+Options];To;;0;[o; ;[I"6{Argument Converters}[#label-Argument+Converters];To;;0;[o; ;[I"{Help}[#label-Help];To;;0;[o; ;[I"<{Top List and Base List}[#label-Top+List+and+Base+List];To;;0;[o; ;[I"H{Methods for Defining Options}[#label-Methods+for+Defining+Options];To;;0;[o; ;[I"{Parsing}[#label-Parsing];To;;;;[o;;0;[o; ;[I",{Method parse!}[#label-Method+parse-21];To;;0;[o; ;[I"({Method parse}[#label-Method+parse];To;;0;[o; ;[I",{Method order!}[#label-Method+order-21];To;;0;[o; ;[I"({Method order}[#label-Method+order];To;;0;[o; ;[I"0{Method permute!}[#label-Method+permute-21];To;;0;[o; ;[I",{Method permute}[#label-Method+permute];T@ S; ; i;I"To Begin With;T@ o; ;[I"To use +OptionParser+:;T@ o;;:NUMBER;[ o;;0;[o; ;[I"%Require the +OptionParser+ code.;To;;0;[o; ;[I"%Create an +OptionParser+ object.;To;;0;[o; ;[I" Define one or more options.;To;;0;[o; ;[I"Parse the command line.;T@ o; ;[I"9File +basic.rb+ defines three options, <tt>-x</tt>, ;TI"C<tt>-y</tt>, and <tt>-z</tt>, each with a descriptive string, ;TI"and each with a block.;T@ o;;[I"&# Require the OptionParser code. ;TI"require 'optparse' ;TI"&# Create an OptionParser object. ;TI"parser = OptionParser.new ;TI"## Define one or more options. ;TI"0parser.on('-x', 'Whether to X') do |value| ;TI" p ['x', value] ;TI" end ;TI"0parser.on('-y', 'Whether to Y') do |value| ;TI" p ['y', value] ;TI" end ;TI"0parser.on('-z', 'Whether to Z') do |value| ;TI" p ['z', value] ;TI" end ;TI":# Parse the command line and return pared-down ARGV. ;TI"p parser.parse! ;T;0o; ;[I"KFrom these defined options, the parser automatically builds help text:;T@ o;;[ I"$ ruby basic.rb --help ;TI"Usage: basic [options] ;TI"7 -x Whether to X ;TI"7 -y Whether to Y ;TI"7 -z Whether to Z ;T;0o; ;[I"-When an option is found during parsing, ;TI"Ithe block defined for the option is called with the argument value. ;TI"+An invalid option raises an exception.;T@ o; ;[ I"@Method #parse!, which is used most often in this tutorial, ;TI"=removes from +ARGV+ the options and arguments it finds, ;TI"Nleaving other non-option arguments for the program to handle on its own. ;TI":The method returns the possibly-reduced +ARGV+ array.;T@ o; ;[I"Executions:;T@ o;;[I"$ ruby basic.rb -x -z ;TI"["x", true] ;TI"["z", true] ;TI"[] ;TI"$ ruby basic.rb -z -y -x ;TI"["z", true] ;TI"["y", true] ;TI"["x", true] ;TI"[] ;TI"7$ ruby basic.rb -x input_file.txt output_file.txt ;TI"["x", true] ;TI"+["input_file.txt", "output_file.txt"] ;TI"$ ruby basic.rb -a ;TI"Obasic.rb:16:in `<main>': invalid option: -a (OptionParser::InvalidOption) ;T;0S; ; i;I"Defining Options;T@ o; ;[I"8A common way to define an option in +OptionParser+ ;TI"-is with instance method OptionParser#on.;T@ o; ;[I";The method may be called with any number of arguments ;TI"$(whose order does not matter), ;TI"Cand may also have a trailing optional keyword argument +into+.;T@ o; ;[I"JThe given arguments determine the characteristics of the new option. ;TI"These may include:;T@ o;;;;[o;;0;[o; ;[I"$One or more short option names.;To;;0;[o; ;[I"#One or more long option names.;To;;0;[o; ;[I"XWhether the option takes no argument, an optional argument, or a required argument.;To;;0;[o; ;[I")Acceptable _forms_ for the argument.;To;;0;[o; ;[I"*Acceptable _values_ for the argument.;To;;0;[o; ;[I"IA proc or method to be called when the parser encounters the option.;To;;0;[o; ;[I"(String descriptions for the option.;T@ S; ; i;I"Option Names;T@ o; ;[I";You can give an option one or more names of two types:;T@ o;;;;[o;;0;[o; ;[I"FShort (1-character) name, beginning with one hyphen (<tt>-</tt>).;To;;0;[o; ;[I"KLong (multi-character) name, beginning with two hyphens (<tt>--</tt>).;T@ S; ; i ;I"Short Option Names;T@ o; ;[I"EA short option name consists of a hyphen and a single character.;T@ o; ;[I"File +short_names.rb+ ;TI"7defines an option with a short name, <tt>-x</tt>, ;TI"Yand an option with two short names (aliases, in effect) <tt>-y</tt> and <tt>-z</tt>.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI".parser.on('-x', 'Short name') do |value| ;TI" p ['x', value] ;TI" end ;TI"9parser.on('-1', '-%', 'Two short names') do |value| ;TI" p ['-1 or -%', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I""$ ruby short_names.rb --help ;TI""Usage: short_names [options] ;TI"5 -x Short name ;TI": -1, -% Two short names ;TI"$ ruby short_names.rb -x ;TI"["x", true] ;TI"$ ruby short_names.rb -1 ;TI"["-1 or -%", true] ;TI"$ ruby short_names.rb -% ;TI"["-1 or -%", true] ;T;0o; ;[I"/Multiple short names can "share" a hyphen:;T@ o;;[ I" $ ruby short_names.rb -x1% ;TI"["x", true] ;TI"["-1 or -%", true] ;TI"["-1 or -%", true] ;T;0S; ; i ;I"Long Option Names;T@ o; ;[I"MA long option name consists of two hyphens and a one or more characters ;TI"&(usually two or more characters).;T@ o; ;[I"File +long_names.rb+ ;TI"9defines an option with a long name, <tt>--xxx</tt>, ;TI"^and an option with two long names (aliases, in effect) <tt>--y1%</tt> and <tt>--z2#</tt>.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"0parser.on('--xxx', 'Long name') do |value| ;TI" p ['-xxx', value] ;TI" end ;TI">parser.on('--y1%', '--z2#', "Two long names") do |value| ;TI"# p ['--y1% or --z2#', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I"!$ ruby long_names.rb --help ;TI"!Usage: long_names [options] ;TI"4 --xxx Long name ;TI"9 --y1%, --z2# Two long names ;TI" $ ruby long_names.rb --xxx ;TI"["-xxx", true] ;TI" $ ruby long_names.rb --y1% ;TI"["--y1% or --z2#", true] ;TI" $ ruby long_names.rb --z2# ;TI"["--y1% or --z2#", true] ;T;0o; ;[I"GA long name may be defined with both positive and negative senses.;T@ o; ;[I"IFile +long_with_negation.rb+ defines an option that has both senses.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"Fparser.on('--[no-]binary', 'Long name with negation') do |value| ;TI" p [value, value.class] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I")$ ruby long_with_negation.rb --help ;TI")Usage: long_with_negation [options] ;TI"B --[no-]binary Long name with negation ;TI"+$ ruby long_with_negation.rb --binary ;TI"[true, TrueClass] ;TI".$ ruby long_with_negation.rb --no-binary ;TI"[false, FalseClass] ;T;0S; ; i ;I"Mixing Option Names;T@ o; ;[I">Many developers like to mix short and long option names, ;TI"Fso that a short name is in effect an abbreviation of a long name.;T@ o; ;[I"File +mixed_names.rb+ ;TI"Adefines options that each have both a short and a long name.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"Hparser.on('-x', '--xxx', 'Short and long, no argument') do |value| ;TI" p ['--xxx', value] ;TI" end ;TI"Qparser.on('-yYYY', '--yyy', 'Short and long, required argument') do |value| ;TI" p ['--yyy', value] ;TI" end ;TI"Tparser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') do |value| ;TI" p ['--zzz', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I""$ ruby mixed_names.rb --help ;TI""Usage: mixed_names [options] ;TI"F -x, --xxx Short and long, no argument ;TI"L -y, --yyyYYY Short and long, required argument ;TI"L -z, --zzz [ZZZ] Short and long, optional argument ;TI"$ ruby mixed_names.rb -x ;TI"["--xxx", true] ;TI"!$ ruby mixed_names.rb --xxx ;TI"["--xxx", true] ;TI"$ ruby mixed_names.rb -y ;TI"Ymixed_names.rb:12:in `<main>': missing argument: -y (OptionParser::MissingArgument) ;TI""$ ruby mixed_names.rb -y FOO ;TI"["--yyy", "FOO"] ;TI"!$ ruby mixed_names.rb --yyy ;TI"\mixed_names.rb:12:in `<main>': missing argument: --yyy (OptionParser::MissingArgument) ;TI"%$ ruby mixed_names.rb --yyy BAR ;TI"["--yyy", "BAR"] ;TI"$ ruby mixed_names.rb -z ;TI"["--zzz", nil] ;TI""$ ruby mixed_names.rb -z BAZ ;TI"["--zzz", "BAZ"] ;TI"!$ ruby mixed_names.rb --zzz ;TI"["--zzz", nil] ;TI"%$ ruby mixed_names.rb --zzz BAT ;TI"["--zzz", "BAT"] ;T;0S; ; i ;I"Option Name Abbreviations;T@ o; ;[I"KBy default, abbreviated option names on the command-line are allowed. ;TI"QAn abbreviated name is valid if it is unique among abbreviated option names.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI".parser.on('-n', '--dry-run',) do |value| ;TI" p ['--dry-run', value] ;TI" end ;TI",parser.on('-d', '--draft',) do |value| ;TI" p ['--draft', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I""$ ruby name_abbrev.rb --help ;TI""Usage: name_abbrev [options] ;TI" -n, --dry-run ;TI" -d, --draft ;TI"$ ruby name_abbrev.rb -n ;TI"["--dry-run", true] ;TI"%$ ruby name_abbrev.rb --dry-run ;TI"["--dry-run", true] ;TI"$ ruby name_abbrev.rb -d ;TI"["--draft", true] ;TI"#$ ruby name_abbrev.rb --draft ;TI"["--draft", true] ;TI"$ ruby name_abbrev.rb --d ;TI"Yname_abbrev.rb:9:in `<main>': ambiguous option: --d (OptionParser::AmbiguousOption) ;TI" $ ruby name_abbrev.rb --dr ;TI"Zname_abbrev.rb:9:in `<main>': ambiguous option: --dr (OptionParser::AmbiguousOption) ;TI"!$ ruby name_abbrev.rb --dry ;TI"["--dry-run", true] ;TI"!$ ruby name_abbrev.rb --dra ;TI"["--draft", true] ;T;0o; ;[I"?You can disable abbreviation using method +require_exact+.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI".parser.on('-n', '--dry-run',) do |value| ;TI" p ['--dry-run', value] ;TI" end ;TI",parser.on('-d', '--draft',) do |value| ;TI" p ['--draft', value] ;TI" end ;TI"!parser.require_exact = true ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[ I"($ ruby no_abbreviation.rb --dry-ru ;TI"_no_abbreviation.rb:10:in `<main>': invalid option: --dry-ru (OptionParser::InvalidOption) ;TI")$ ruby no_abbreviation.rb --dry-run ;TI"["--dry-run", true] ;T;0S; ; i;I"Option Arguments;T@ o; ;[I"RAn option may take no argument, a required argument, or an optional argument.;T@ S; ; i ;I"Option with No Argument;T@ o; ;[I"<All the examples above define options with no argument.;T@ S; ; i ;I""Option with Required Argument;T@ o; ;[I"FSpecify a required argument for an option by adding a dummy word ;TI"to its name definition.;T@ o; ;[I"6File +required_argument.rb+ defines two options; ;TI"Yeach has a required argument because the name definition has a following dummy word.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"Qparser.on('-x XXX', '--xxx', 'Required argument via short name') do |value| ;TI" p ['--xxx', value] ;TI" end ;TI"Nparser.on('-y', '--y YYY', 'Required argument via long name') do |value| ;TI" p ['--yyy', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"<When an option is found, the given argument is yielded.;T@ o; ;[I"Executions:;T@ o;;[ I"($ ruby required_argument.rb --help ;TI"(Usage: required_argument [options] ;TI"K -x, --xxx XXX Required argument via short name ;TI"J -y, --y YYY Required argument via long name ;TI"($ ruby required_argument.rb -x AAA ;TI"["--xxx", "AAA"] ;TI"($ ruby required_argument.rb -y BBB ;TI"["--yyy", "BBB"] ;T;0o; ;[I"2Omitting a required argument raises an error:;T@ o;;[I"$$ ruby required_argument.rb -x ;TI"^required_argument.rb:9:in `<main>': missing argument: -x (OptionParser::MissingArgument) ;T;0S; ; i ;I""Option with Optional Argument;T@ o; ;[I"GSpecify an optional argument for an option by adding a dummy word ;TI"8enclosed in square brackets to its name definition.;T@ o; ;[I"6File +optional_argument.rb+ defines two options; ;TI"Zeach has an optional argument because the name definition has a following dummy word ;TI"in square brackets.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"Tparser.on('-x [XXX]', '--xxx', 'Optional argument via short name') do |value| ;TI" p ['--xxx', value] ;TI" end ;TI"Rparser.on('-y', '--yyy [YYY]', 'Optional argument via long name') do |value| ;TI" p ['--yyy', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"JWhen an option with an argument is found, the given argument yielded.;T@ o; ;[I"Executions:;T@ o;;[ I"($ ruby optional_argument.rb --help ;TI"(Usage: optional_argument [options] ;TI"L -x, --xxx [XXX] Optional argument via short name ;TI"J -y, --yyy [YYY] Optional argument via long name ;TI"($ ruby optional_argument.rb -x AAA ;TI"["--xxx", "AAA"] ;TI"($ ruby optional_argument.rb -y BBB ;TI"["--yyy", "BBB"] ;T;0o; ;[I";Omitting an optional argument does not raise an error.;T@ S; ; i ;I"Argument Abbreviations;T@ o; ;[I"4Specify an argument list as an Array or a Hash.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"Vparser.on('-x', '--xxx=VALUE', %w[ABC def], 'Argument abbreviations') do |value| ;TI" p ['--xxx', value] ;TI" end ;TI"eparser.on('-y', '--yyy=VALUE', {"abc"=>"XYZ", def: "FOO"}, 'Argument abbreviations') do |value| ;TI" p ['--yyy', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"DWhen an argument is abbreviated, the expanded argument yielded.;T@ o; ;[I"Executions:;T@ o;;[I",$ ruby argument_abbreviation.rb --help ;TI",Usage: argument_abbreviation [options] ;TI",Usage: argument_abbreviation [options] ;TI"A -x, --xxx=VALUE Argument abbreviations ;TI"A -y, --yyy=VALUE Argument abbreviations ;TI"-$ ruby argument_abbreviation.rb --xxx A ;TI"["--xxx", "ABC"] ;TI"-$ ruby argument_abbreviation.rb --xxx c ;TI"gargument_abbreviation.rb:9:in `<main>': invalid argument: --xxx c (OptionParser::InvalidArgument) ;TI"5$ ruby argument_abbreviation.rb --yyy a --yyy d ;TI"["--yyy", "XYZ"] ;TI"["--yyy", "FOO"] ;T;0S; ; i;I"Argument Values;T@ o; ;[I"3Permissible argument values may be restricted ;TI"*either by specifying explicit values ;TI"?or by providing a pattern that the given value must match.;T@ S; ; i ;I"Explicit Argument Values;T@ o; ;[I";You can specify argument values in either of two ways:;T@ o;;;;[o;;0;[o; ;[I"(Specify values an array of strings.;To;;0;[o; ;[I"Specify values a hash.;T@ S; ; i ;I"Explicit Values in Array;T@ o; ;[I"FYou can specify explicit argument values in an array of strings. ;TI"UThe argument value must be one of those strings, or an unambiguous abbreviation.;T@ o; ;[I"SFile +explicit_array_values.rb+ defines options with explicit argument values.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"Tparser.on('-xXXX', ['foo', 'bar'], 'Values for required argument' ) do |value| ;TI" p ['-x', value] ;TI" end ;TI"Vparser.on('-y [YYY]', ['baz', 'bat'], 'Values for optional argument') do |value| ;TI" p ['-y', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I",$ ruby explicit_array_values.rb --help ;TI",Usage: explicit_array_values [options] ;TI"G -xXXX Values for required argument ;TI"G -y [YYY] Values for optional argument ;TI"($ ruby explicit_array_values.rb -x ;TI"bexplicit_array_values.rb:9:in `<main>': missing argument: -x (OptionParser::MissingArgument) ;TI",$ ruby explicit_array_values.rb -x foo ;TI"["-x", "foo"] ;TI"*$ ruby explicit_array_values.rb -x f ;TI"["-x", "foo"] ;TI",$ ruby explicit_array_values.rb -x bar ;TI"["-x", "bar"] ;TI"+$ ruby explicit_array_values.rb -y ba ;TI"iexplicit_array_values.rb:9:in `<main>': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) ;TI",$ ruby explicit_array_values.rb -x baz ;TI"fexplicit_array_values.rb:9:in `<main>': invalid argument: -x baz (OptionParser::InvalidArgument) ;T;0S; ; i ;I"Explicit Values in Hash;T@ o; ;[I"JYou can specify explicit argument values in a hash with string keys. ;TI"QThe value passed must be one of those keys, or an unambiguous abbreviation; ;TI"6the value yielded will be the value for that key.;T@ o; ;[I"RFile +explicit_hash_values.rb+ defines options with explicit argument values.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"Vparser.on('-xXXX', {foo: 0, bar: 1}, 'Values for required argument' ) do |value| ;TI" p ['-x', value] ;TI" end ;TI"Xparser.on('-y [YYY]', {baz: 2, bat: 3}, 'Values for optional argument') do |value| ;TI" p ['-y', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I"+$ ruby explicit_hash_values.rb --help ;TI"+Usage: explicit_hash_values [options] ;TI"G -xXXX Values for required argument ;TI"G -y [YYY] Values for optional argument ;TI"'$ ruby explicit_hash_values.rb -x ;TI"aexplicit_hash_values.rb:9:in `<main>': missing argument: -x (OptionParser::MissingArgument) ;TI"+$ ruby explicit_hash_values.rb -x foo ;TI"["-x", 0] ;TI")$ ruby explicit_hash_values.rb -x f ;TI"["-x", 0] ;TI"+$ ruby explicit_hash_values.rb -x bar ;TI"["-x", 1] ;TI"+$ ruby explicit_hash_values.rb -x baz ;TI"eexplicit_hash_values.rb:9:in `<main>': invalid argument: -x baz (OptionParser::InvalidArgument) ;TI"'$ ruby explicit_hash_values.rb -y ;TI"["-y", nil] ;TI"+$ ruby explicit_hash_values.rb -y baz ;TI"["-y", 2] ;TI"+$ ruby explicit_hash_values.rb -y bat ;TI"["-y", 3] ;TI"*$ ruby explicit_hash_values.rb -y ba ;TI"hexplicit_hash_values.rb:9:in `<main>': ambiguous argument: -y ba (OptionParser::AmbiguousArgument) ;TI"+$ ruby explicit_hash_values.rb -y bam ;TI"["-y", nil] ;T;0S; ; i ;I"Argument Value Patterns;T@ o; ;[I"2You can restrict permissible argument values ;TI"?by specifying a Regexp that the given argument must match.;T@ o; ;[I"KFile +matched_values.rb+ defines options with matched argument values.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"Aparser.on('--xxx XXX', /foo/i, 'Matched values') do |value| ;TI" p ['--xxx', value] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I"%$ ruby matched_values.rb --help ;TI"%Usage: matched_values [options] ;TI"9 --xxx XXX Matched values ;TI"($ ruby matched_values.rb --xxx foo ;TI"["--xxx", "foo"] ;TI"($ ruby matched_values.rb --xxx FOO ;TI"["--xxx", "FOO"] ;TI"($ ruby matched_values.rb --xxx bar ;TI"bmatched_values.rb:6:in `<main>': invalid argument: --xxx bar (OptionParser::InvalidArgument) ;T;0S; ; i;I"Keyword Argument +into+;T@ o; ;[I"VIn parsing options, you can add keyword option +into+ with a hash-like argument; ;TI";each parsed option will be added as a name/value pair.;T@ o; ;[I"This is useful for:;T@ o;;;;[o;;0;[o; ;[I"Collecting options.;To;;0;[o; ;[I""Checking for missing options.;To;;0;[o; ;[I"*Providing default values for options.;T@ S; ; i ;I"Collecting Options;T@ o; ;[I"4Use keyword argument +into+ to collect options.;T@ o;;[ I"require 'optparse' ;TI"parser = OptionParser.new ;TI"=parser.on('-x', '--xxx', 'Short and long, no argument') ;TI"Fparser.on('-yYYY', '--yyy', 'Short and long, required argument') ;TI"Iparser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') ;TI"options = {} ;TI""parser.parse!(into: options) ;TI"p options ;T;0o; ;[I"Executions:;T@ o;;[I"($ ruby collected_options.rb --help ;TI"Usage: into [options] ;TI"F -x, --xxx Short and long, no argument ;TI"L -y, --yyyYYY Short and long, required argument ;TI"L -z, --zzz [ZZZ] Short and long, optional argument ;TI"'$ ruby collected_options.rb --xxx ;TI"{:xxx=>true} ;TI"1$ ruby collected_options.rb --xxx --yyy FOO ;TI"{:xxx=>true, :yyy=>"FOO"} ;TI";$ ruby collected_options.rb --xxx --yyy FOO --zzz Bar ;TI",{:xxx=>true, :yyy=>"FOO", :zzz=>"Bar"} ;TI";$ ruby collected_options.rb --xxx --yyy FOO --yyy BAR ;TI"{:xxx=>true, :yyy=>"BAR"} ;T;0o; ;[I"RNote in the last execution that the argument value for option <tt>--yyy</tt> ;TI"was overwritten.;T@ S; ; i ;I"!Checking for Missing Options;T@ o; ;[I"<Use the collected options to check for missing options.;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"=parser.on('-x', '--xxx', 'Short and long, no argument') ;TI"Fparser.on('-yYYY', '--yyy', 'Short and long, required argument') ;TI"Iparser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') ;TI"options = {} ;TI""parser.parse!(into: options) ;TI"%required_options = [:xxx, :zzz] ;TI"7missing_options = required_options - options.keys ;TI"#unless missing_options.empty? ;TI"; fail "Missing required options: #{missing_options}" ;TI" end ;T;0o; ;[I"Executions:;T@ o;;[I"&$ ruby missing_options.rb --help ;TI"&Usage: missing_options [options] ;TI"F -x, --xxx Short and long, no argument ;TI"L -y, --yyyYYY Short and long, required argument ;TI"L -z, --zzz [ZZZ] Short and long, optional argument ;TI")$ ruby missing_options.rb --yyy FOO ;TI"^missing_options.rb:11:in `<main>': Missing required options: [:xxx, :zzz] (RuntimeError) ;T;0S; ; i ;I"Default Values for Options;T@ o; ;[I"IInitialize the +into+ argument to define default values for options.;T@ o;;[ I"require 'optparse' ;TI"parser = OptionParser.new ;TI"=parser.on('-x', '--xxx', 'Short and long, no argument') ;TI"Fparser.on('-yYYY', '--yyy', 'Short and long, required argument') ;TI"Iparser.on('-z [ZZZ]', '--zzz', 'Short and long, optional argument') ;TI"(options = {yyy: 'AAA', zzz: 'BBB'} ;TI""parser.parse!(into: options) ;TI"p options ;T;0o; ;[I"Executions:;T@ o;;[I"%$ ruby default_values.rb --help ;TI"%Usage: default_values [options] ;TI"F -x, --xxx Short and long, no argument ;TI"L -y, --yyyYYY Short and long, required argument ;TI"L -z, --zzz [ZZZ] Short and long, optional argument ;TI"($ ruby default_values.rb --yyy FOO ;TI" {:yyy=>"FOO", :zzz=>"BBB"} ;T;0S; ; i;I"Argument Converters;T@ o; ;[I"@An option can specify that its argument is to be converted ;TI"@from the default +String+ to an instance of another class. ;TI"/There are a number of built-in converters.;T@ o; ;[I"Example: File +date.rb+ ;TI"Mdefines an option whose argument is to be converted to a +Date+ object. ;TI"4The argument is converted by method Date#parse.;T@ o;;[I"require 'optparse/date' ;TI"parser = OptionParser.new ;TI"/parser.on('--date=DATE', Date) do |value| ;TI" p [value, value.class] ;TI" end ;TI"parser.parse! ;T;0o; ;[I"Executions:;T@ o;;[I"&$ ruby date.rb --date 2001-02-03 ;TI"A[#<Date: 2001-02-03 ((2451944j,0s,0n),+0s,2299161j)>, Date] ;TI"$$ ruby date.rb --date 20010203 ;TI"A[#<Date: 2001-02-03 ((2451944j,0s,0n),+0s,2299161j)>, Date] ;TI"*$ ruby date.rb --date "3rd Feb 2001" ;TI"A[#<Date: 2001-02-03 ((2451944j,0s,0n),+0s,2299161j)>, Date] ;T;0o; ;[I",You can also define custom converters. ;TI";See {Argument Converters}[./argument_converters.rdoc] ;TI"-for both built-in and custom converters.;T@ S; ; i;I" Help;T@ o; ;[I"F+OptionParser+ makes automatically generated help text available.;T@ o; ;[I"The help text consists of:;T@ o;;;;[ o;;0;[o; ;[I"!A banner, showing the usage.;To;;0;[o; ;[I"!Option short and long names.;To;;0;[o; ;[I"!Option dummy argument names.;To;;0;[o; ;[I"Option descriptions.;T@ o; ;[I"Example code:;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"parser.on( ;TI" '-x', '--xxx', ;TI"7 'Adipiscing elit. Aenean commodo ligula eget.', ;TI"5 'Aenean massa. Cum sociis natoque penatibus', ;TI" ) ;TI"parser.on( ;TI" '-y', '--yyy YYY', ;TI"3 'Lorem ipsum dolor sit amet, consectetuer.' ;TI") ;TI"parser.on( ;TI" '-z', '--zzz [ZZZ]', ;TI"4 'Et magnis dis parturient montes, nascetur', ;TI"5 'ridiculus mus. Donec quam felis, ultricies', ;TI"3 'nec, pellentesque eu, pretium quis, sem.', ;TI" ) ;TI"parser.parse! ;T;0o; ;[I"NThe option names and dummy argument names are defined as described above.;T@ o; ;[I"ZThe option description consists of the strings that are not themselves option names; ;TI":An option can have more than one description string. ;TI"Execution:;T@ o;;[I"Usage: help [options] ;TI"W -x, --xxx Adipiscing elit. Aenean commodo ligula eget. ;TI"U Aenean massa. Cum sociis natoque penatibus ;TI"T -y, --yyy YYY Lorem ipsum dolor sit amet, consectetuer. ;TI"T -z, --zzz [ZZZ] Et magnis dis parturient montes, nascetur ;TI"U ridiculus mus. Donec quam felis, ultricies ;TI"S nec, pellentesque eu, pretium quis, sem. ;T;0o; ;[I"9The program name is included in the default banner: ;TI"0<tt>Usage: #{program_name} [options]</tt>; ;TI"%you can change the program name.;T@ o;;[ I"require 'optparse' ;TI"parser = OptionParser.new ;TI"2parser.program_name = 'help_program_name.rb' ;TI"parser.parse! ;T;0o; ;[I"Execution:;T@ o;;[I"($ ruby help_program_name.rb --help ;TI"+Usage: help_program_name.rb [options] ;T;0o; ;[I"+You can also change the entire banner.;T@ o;;[ I"require 'optparse' ;TI"parser = OptionParser.new ;TI"2parser.banner = "Usage: ruby help_banner.rb" ;TI"parser.parse! ;T;0o; ;[I"Execution:;T@ o;;[I""$ ruby help_banner.rb --help ;TI" Usage: ruby help_banner.rb ;T;0o; ;[I"8By default, the option names are indented 4 spaces ;TI":and the width of the option-names field is 32 spaces.;T@ o; ;[I"9You can change these values, along with the banner, ;TI"/by passing parameters to OptionParser.new.;T@ o;;[I"require 'optparse' ;TI" parser = OptionParser.new( ;TI"1 'ruby help_format.rb [options]', # Banner ;TI"B 20, # Width of options field ;TI"; ' ' * 2 # Indentation ;TI") ;TI"parser.on( ;TI" '-x', '--xxx', ;TI"7 'Adipiscing elit. Aenean commodo ligula eget.', ;TI"5 'Aenean massa. Cum sociis natoque penatibus', ;TI" ) ;TI"parser.on( ;TI" '-y', '--yyy YYY', ;TI"3 'Lorem ipsum dolor sit amet, consectetuer.' ;TI") ;TI"parser.on( ;TI" '-z', '--zzz [ZZZ]', ;TI"4 'Et magnis dis parturient montes, nascetur', ;TI"5 'ridiculus mus. Donec quam felis, ultricies', ;TI"3 'nec, pellentesque eu, pretium quis, sem.', ;TI" ) ;TI"parser.parse! ;T;0o; ;[I"Execution:;T@ o;;[ I""$ ruby help_format.rb --help ;TI"#ruby help_format.rb [options] ;TI"I -x, --xxx Adipiscing elit. Aenean commodo ligula eget. ;TI"G Aenean massa. Cum sociis natoque penatibus ;TI"F -y, --yyy YYY Lorem ipsum dolor sit amet, consectetuer. ;TI"F -z, --zzz [ZZZ] Et magnis dis parturient montes, nascetur ;TI"G ridiculus mus. Donec quam felis, ultricies ;TI"E nec, pellentesque eu, pretium quis, sem. ;T;0S; ; i;I"Top List and Base List;T@ o; ;[I"OAn +OptionParser+ object maintains a stack of OptionParser::List objects, ;TI"=each of which has a collection of zero or more options. ;TI"IIt is unlikely that you'll need to add or take away from that stack.;T@ o; ;[I"The stack includes:;T@ o;;;;[o;;0;[o; ;[I"6The <em>top list</em>, given by OptionParser#top.;To;;0;[o; ;[I"8The <em>base list</em>, given by OptionParser#base.;T@ o; ;[I"KWhen +OptionParser+ builds its help text, the options in the top list ;TI"$precede those in the base list.;T@ S; ; i;I"!Methods for Defining Options;T@ o; ;[I"WOption-defining methods allow you to create an option, and also append/prepend it ;TI"3to the top list or append it to the base list.;T@ o; ;[I"]Each of these next three methods accepts a sequence of parameter arguments and a block, ;TI"Qcreates an option object using method OptionParser#make_switch (see below), ;TI"$and returns the created option:;T@ o;;;;[o;;0;[o; ;[I"L\Method OptionParser#define appends the created option to the top list.;T@ o;;0;[o; ;[I"R\Method OptionParser#define_head prepends the created option to the top list.;T@ o;;0;[o; ;[I"R\Method OptionParser#define_tail appends the created option to the base list.;T@ o; ;[I"@These next three methods are identical to the three above, ;TI"$except for their return values:;T@ o;;;;[o;;0;[o; ;[I"I\Method OptionParser#on is identical to method OptionParser#define, ;TI"5except that it returns the parser object +self+.;T@ o;;0;[o; ;[I"S\Method OptionParser#on_head is identical to method OptionParser#define_head, ;TI"5except that it returns the parser object +self+.;T@ o;;0;[o; ;[I"S\Method OptionParser#on_tail is identical to method OptionParser#define_tail, ;TI"5except that it returns the parser object +self+.;T@ o; ;[I"4Though you may never need to call it directly, ;TI"3here's the core method for defining an option:;T@ o;;;;[o;;0;[o; ;[I"R\Method OptionParser#make_switch accepts an array of parameters and a block. ;TI"DSee {Parameters for New Options}[optparse/option_params.rdoc]. ;TI"2This method is unlike others here in that it:;To;;;;[o;;0;[o; ;[I".Accepts an <em>array of parameters</em>; ;TI">others accept a <em>sequence of parameter arguments</em>.;To;;0;[o; ;[ I"<Returns an array containing the created option object, ;TI"%option names, and other values; ;TI"4others return either the created option object ;TI"!or the parser object +self+.;T@ S; ; i;I"Parsing;T@ o; ;[I"9+OptionParser+ has six instance methods for parsing.;T@ o; ;[I"8Three have names ending with a "bang" (<tt>!</tt>):;T@ o;;;;[o;;0;[o; ;[I"parse!;To;;0;[o; ;[I"order!;To;;0;[o; ;[I" permute!;T@ o; ;[I"Each of these methods:;T@ o;;;;[o;;0;[o; ;[I";Accepts an optional array of string arguments +argv+; ;TI"Nif not given, +argv+ defaults to the value of OptionParser#default_argv, ;TI"!whose initial value is ARGV.;To;;0;[o; ;[I"1Accepts an optional keyword argument +into+ ;TI"A(see {Keyword Argument into}[#label-Keyword+Argument+into]).;To;;0;[o; ;[I"9Returns +argv+, possibly with some elements removed.;T@ o; ;[I"CThe three other methods have names _not_ ending with a "bang":;T@ o;;;;[o;;0;[o; ;[I" parse;To;;0;[o; ;[I" order;To;;0;[o; ;[I"permute;T@ o; ;[I"Each of these methods:;T@ o;;;;[o;;0;[o; ;[I"*Accepts an array of string arguments ;TI"(_or_ zero or more string arguments.;To;;0;[o; ;[I"GAccepts an optional keyword argument +into+ and its value _into_. ;TI"A(see {Keyword Argument into}[#label-Keyword+Argument+into]).;To;;0;[o; ;[I"9Returns +argv+, possibly with some elements removed.;T@ S; ; i ;I"\Method +parse!+;T@ o; ;[I"\Method +parse!+:;T@ o;;;;[o;;0;[o; ;[I";Accepts an optional array of string arguments +argv+; ;TI"Nif not given, +argv+ defaults to the value of OptionParser#default_argv, ;TI"!whose initial value is ARGV.;To;;0;[o; ;[I"1Accepts an optional keyword argument +into+ ;TI"A(see {Keyword Argument into}[#label-Keyword+Argument+into]).;To;;0;[o; ;[I"9Returns +argv+, possibly with some elements removed.;T@ o; ;[I"PThe method processes the elements in +argv+ beginning at <tt>argv[0]</tt>, ;TI"(and ending, by default, at the end.;T@ o; ;[I";Otherwise processing ends and the method returns when:;T@ o;;;;[o;;0;[o; ;[I"3The terminator argument <tt>--</tt> is found; ;TI":the terminator argument is removed before the return.;To;;0;[o; ;[ I"7Environment variable +POSIXLY_CORRECT+ is defined ;TI")and a non-option argument is found; ;TI"-the non-option argument is not removed. ;TI"=Note that the _value_ of that variable does not matter, ;TI"&as only its existence is checked.;T@ o; ;[I"File +parse_bang.rb+:;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"#parser.on('--xxx') do |value| ;TI" p ['--xxx', value] ;TI" end ;TI"'parser.on('--yyy YYY') do |value| ;TI" p ['--yyy', value] ;TI" end ;TI")parser.on('--zzz [ZZZ]') do |value| ;TI" p ['--zzz', value] ;TI" end ;TI"ret = parser.parse! ;TI",puts "Returned: #{ret} (#{ret.class})" ;T;0o; ;[I" Help:;T@ o;;[ I"!$ ruby parse_bang.rb --help ;TI"!Usage: parse_bang [options] ;TI" --xxx ;TI" --yyy YYY ;TI" --zzz [ZZZ] ;T;0o; ;[I"Default behavior:;T@ o;;[ I"S$ ruby parse_bang.rb input_file.txt output_file.txt --xxx --yyy FOO --zzz BAR ;TI"["--xxx", true] ;TI"["--yyy", "FOO"] ;TI"["--zzz", "BAR"] ;TI"=Returned: ["input_file.txt", "output_file.txt"] (Array) ;T;0o; ;[I"-Processing ended by terminator argument:;T@ o;;[ I"V$ ruby parse_bang.rb input_file.txt output_file.txt --xxx --yyy FOO -- --zzz BAR ;TI"["--xxx", true] ;TI"["--yyy", "FOO"] ;TI"MReturned: ["input_file.txt", "output_file.txt", "--zzz", "BAR"] (Array) ;T;0o; ;[I"LProcessing ended by non-option found when +POSIXLY_CORRECT+ is defined:;T@ o;;[I"]$ POSIXLY_CORRECT=true ruby parse_bang.rb --xxx input_file.txt output_file.txt -yyy FOO ;TI"["--xxx", true] ;TI"LReturned: ["input_file.txt", "output_file.txt", "-yyy", "FOO"] (Array) ;T;0S; ; i ;I"\Method +parse+;T@ o; ;[I"\Method +parse+:;T@ o;;;;[o;;0;[o; ;[I"*Accepts an array of string arguments ;TI"(_or_ zero or more string arguments.;To;;0;[o; ;[I"GAccepts an optional keyword argument +into+ and its value _into_. ;TI"A(see {Keyword Argument into}[#label-Keyword+Argument+into]).;To;;0;[o; ;[I"9Returns +argv+, possibly with some elements removed.;T@ o; ;[I"QIf given an array +ary+, the method forms array +argv+ as <tt>ary.dup</tt>. ;TI"HIf given zero or more string arguments, those arguments are formed ;TI"into array +argv+.;T@ o; ;[I"The method calls;T@ o;;[I"parse!(argv, into: into) ;T;0o; ;[I"6Note that environment variable +POSIXLY_CORRECT+ ;TI"9and the terminator argument <tt>--</tt> are honored.;T@ o; ;[I"File +parse.rb+:;T@ o;;[I"require 'optparse' ;TI"parser = OptionParser.new ;TI"#parser.on('--xxx') do |value| ;TI" p ['--xxx', value] ;TI" end ;TI"'parser.on('--yyy YYY') do |value| ;TI" p ['--yyy', value] ;TI" end ;TI")parser.on('--zzz [ZZZ]') do |value| ;TI" p ['--zzz', value] ;TI" end ;TI"ret = parser.parse(ARGV) ;TI",puts "Returned: #{ret} (#{ret.class})" ;T;0o; ;[I" Help:;T@ o;;[ I"$ ruby parse.rb --help ;TI"Usage: parse [options] ;TI" --xxx ;TI" --yyy YYY ;TI" --zzz [ZZZ] ;T;0o; ;[I"Default behavior:;T@ o;;[ I"N$ ruby parse.rb input_file.txt output_file.txt --xxx --yyy FOO --zzz BAR ;TI"["--xxx", true] ;TI"["--yyy", "FOO"] ;TI"["--zzz", "BAR"] ;TI"=Returned: ["input_file.txt", "output_file.txt"] (Array) ;T;0o; ;[I"-Processing ended by terminator argument:;T@ o;;[ I"Q$ ruby parse.rb input_file.txt output_file.txt --xxx --yyy FOO -- --zzz BAR ;TI"["--xxx", true] ;TI"["--yyy", "FOO"] ;TI"MReturned: ["input_file.txt", "output_file.txt", "--zzz", "BAR"] (Array) ;T;0o; ;[I"LProcessing ended by non-option found when +POSIXLY_CORRECT+ is defined:;T@ o;;[I"X$ POSIXLY_CORRECT=true ruby parse.rb --xxx input_file.txt output_file.txt -yyy FOO ;TI"["--xxx", true] ;TI"LReturned: ["input_file.txt", "output_file.txt", "-yyy", "FOO"] (Array) ;T;0S; ; i ;I"\Method +order!+;T@ o; ;[I"ICalling method OptionParser#order! gives exactly the same result as ;TI"Bcalling method OptionParser#parse! with environment variable ;TI"+POSIXLY_CORRECT+ defined.;T@ S; ; i ;I"\Method +order+;T@ o; ;[I"HCalling method OptionParser#order gives exactly the same result as ;TI"Acalling method OptionParser#parse with environment variable ;TI"+POSIXLY_CORRECT+ defined.;T@ S; ; i ;I"\Method +permute!+;T@ o; ;[I"KCalling method OptionParser#permute! gives exactly the same result as ;TI"Bcalling method OptionParser#parse! with environment variable ;TI"%+POSIXLY_CORRECT+ _not_ defined.;T@ S; ; i ;I"\Method +permute+;T@ o; ;[I"JCalling method OptionParser#permute gives exactly the same result as ;TI"Acalling method OptionParser#parse with environment variable ;TI"%+POSIXLY_CORRECT+ _not_ defined.;T: @file@:0@omit_headings_from_table_of_contents_below0