class OptionParser
OptionParser¶↑
New toOptionParser?¶↑
See theTutorial.
Introduction¶↑
OptionParser is a class for command-line option analysis. It is much more advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented solution.
Features¶↑
The argument specification and the code to handle it are written in the same place.
It can output an option summary; you don’t need to maintain this string separately.
Optional and mandatory arguments are specified very gracefully.
Arguments can be automatically converted to a specified class.
Arguments can be restricted to a certain set.
All of these features are demonstrated in the examples below. Seemake_switch for full documentation.
Minimal example¶↑
require'optparse'options = {}OptionParser.newdo|parser|parser.banner ="Usage: example.rb [options]"parser.on("-v","--[no-]verbose","Run verbosely")do|v|options[:verbose] =vendend.parse!poptionspARGV
Generating Help¶↑
OptionParser can be used to automatically generate help for the commands you write:
require'optparse'Options =Struct.new(:name)classParserdefself.parse(options)args =Options.new("world")opt_parser =OptionParser.newdo|parser|parser.banner ="Usage: example.rb [options]"parser.on("-nNAME","--name=NAME","Name to say hello to")do|n|args.name =nendparser.on("-h","--help","Prints this help")doputsparserexitendendopt_parser.parse!(options)returnargsendendoptions =Parser.parse%w[--help]#=># Usage: example.rb [options]# -n, --name=NAME Name to say hello to# -h, --help Prints this help
Required Arguments¶↑
For options that require an argument, option specification strings may include an option name in all caps. If an option is used without the required argument, an exception will be raised.
require'optparse'options = {}OptionParser.newdo|parser|parser.on("-r","--require LIBRARY","Require the LIBRARY before executing your script")do|lib|puts"You required #{lib}!"endend.parse!
Used:
$ ruby optparse-test.rb -roptparse-test.rb:9:in '<main>': missing argument: -r (OptionParser::MissingArgument)$ ruby optparse-test.rb -r my-libraryYou required my-library!
Type Coercion¶↑
OptionParser supports the ability to coerce command line arguments into objects for us.
OptionParser comes with a few ready-to-use kinds of type coercion. They are:
Date– Anything accepted byDate.parse(need to requireoptparse/date)DateTime– Anything accepted byDateTime.parse(need to requireoptparse/date)Time– Anything accepted byTime.httpdateorTime.parse(need to requireoptparse/time)URI– Anything accepted byURI.parse(need to requireoptparse/uri)Shellwords– Anything accepted byShellwords.shellwords(need to requireoptparse/shellwords)String– Any non-empty stringInteger– Any integer. Will convert octal. (e.g. 124, -3, 040)Float– Any float. (e.g. 10, 3.14, -100E+13)Numeric– Any integer, float, or rational (1, 3.4, 1/3)DecimalInteger– LikeInteger, but no octal format.OctalInteger– LikeInteger, but no decimal format.DecimalNumeric– Decimal integer or float.TrueClass– Accepts ‘+, yes, true, -, no, false’ and defaults astrueFalseClass– Same asTrueClass, but defaults tofalseArray– Strings separated by ‘,’ (e.g. 1,2,3)Regexp– Regular expressions. Also includes options.
We can also add our own coercions, which we will cover below.
Using Built-in Conversions¶↑
As an example, the built-inTime conversion is used. The other built-in conversions behave in the same way.OptionParser will attempt to parse the argument as aTime. If it succeeds, that time will be passed to the handler block. Otherwise, an exception will be raised.
require'optparse'require'optparse/time'OptionParser.newdo|parser|parser.on("-t","--time [TIME]",Time,"Begin execution at given time")do|time|ptimeendend.parse!
Used:
$ ruby optparse-test.rb -t nonsense... invalid argument: -t nonsense (OptionParser::InvalidArgument)$ ruby optparse-test.rb -t 10-11-122010-11-12 00:00:00 -0500$ ruby optparse-test.rb -t 9:302014-08-13 09:30:00 -0400
Creating Custom Conversions¶↑
Theaccept method onOptionParser may be used to create converters. It specifies which conversion block to call whenever a class is specified. The example below uses it to fetch aUser object before theon handler receives it.
require'optparse'User =Struct.new(:id,:name)deffind_useridnot_found =->{raise"No User Found for id #{id}" } [User.new(1,"Sam"),User.new(2,"Gandalf") ].find(not_found)do|u|u.id==idendendop =OptionParser.newop.accept(User)do|user_id|find_useruser_id.to_iendop.on("--user ID",User)do|user|putsuserendop.parse!
Used:
$ ruby optparse-test.rb --user 1#<struct User id=1, name="Sam">$ ruby optparse-test.rb --user 2#<struct User id=2, name="Gandalf">$ ruby optparse-test.rb --user 3optparse-test.rb:15:in 'block in find_user': No User Found for id 3 (RuntimeError)
Store options to aHash¶↑
Theinto option oforder,parse and so on methods stores command line options into aHash.
require'optparse'options = {}OptionParser.newdo|parser|parser.on('-a')parser.on('-b NUM',Integer)parser.on('-v','--verbose')end.parse!(into:options)poptions
Used:
$ ruby optparse-test.rb -a{:a=>true}$ ruby optparse-test.rb -a -v{:a=>true, :verbose=>true}$ ruby optparse-test.rb -a -b 100{:a=>true, :b=>100}Complete example¶↑
The following example is a complete Ruby program. You can run it and see the effect of specifying various options. This is probably the best way to learn the features ofoptparse.
require'optparse'require'optparse/time'require'ostruct'require'pp'classOptparseExampleVersion ='1.0.0'CODES =%w[iso-2022-jp shift_jis euc-jp utf8 binary]CODE_ALIASES = {"jis"=>"iso-2022-jp","sjis"=>"shift_jis" }classScriptOptionsattr_accessor:library,:inplace,:encoding,:transfer_type,:verbose,:extension,:delay,:time,:record_separator,:listdefinitializeself.library = []self.inplace =falseself.encoding ="utf8"self.transfer_type =:autoself.verbose =falseenddefdefine_options(parser)parser.banner ="Usage: example.rb [options]"parser.separator""parser.separator"Specific options:"# add additional optionsperform_inplace_option(parser)delay_execution_option(parser)execute_at_time_option(parser)specify_record_separator_option(parser)list_example_option(parser)specify_encoding_option(parser)optional_option_argument_with_keyword_completion_option(parser)boolean_verbose_option(parser)parser.separator""parser.separator"Common options:"# No argument, shows at tail. This will print an options summary.# Try it and see!parser.on_tail("-h","--help","Show this message")doputsparserexitend# Another typical switch to print the version.parser.on_tail("--version","Show version")doputsVersionexitendenddefperform_inplace_option(parser)# Specifies an optional option argumentparser.on("-i","--inplace [EXTENSION]","Edit ARGV files in place","(make backup if EXTENSION supplied)")do|ext|self.inplace =trueself.extension =ext||''self.extension.sub!(/\A\.?(?=.)/,".")# Ensure extension begins with dot.endenddefdelay_execution_option(parser)# Cast 'delay' argument to a Float.parser.on("--delay N",Float,"Delay N seconds before executing")do|n|self.delay =nendenddefexecute_at_time_option(parser)# Cast 'time' argument to a Time object.parser.on("-t","--time [TIME]",Time,"Begin execution at given time")do|time|self.time =timeendenddefspecify_record_separator_option(parser)# Cast to octal integer.parser.on("-F","--irs [OCTAL]",OptionParser::OctalInteger,"Specify record separator (default \\0)")do|rs|self.record_separator =rsendenddeflist_example_option(parser)# List of arguments.parser.on("--list x,y,z",Array,"Example 'list' of arguments")do|list|self.list =listendenddefspecify_encoding_option(parser)# Keyword completion. We are specifying a specific set of arguments (CODES# and CODE_ALIASES - notice the latter is a Hash), and the user may provide# the shortest unambiguous text.code_list = (CODE_ALIASES.keys+CODES).join(', ')parser.on("--code CODE",CODES,CODE_ALIASES,"Select encoding","(#{code_list})")do|encoding|self.encoding =encodingendenddefoptional_option_argument_with_keyword_completion_option(parser)# Optional '--type' option argument with keyword completion.parser.on("--type [TYPE]", [:text,:binary,:auto],"Select transfer type (text, binary, auto)")do|t|self.transfer_type =tendenddefboolean_verbose_option(parser)# Boolean switch.parser.on("-v","--[no-]verbose","Run verbosely")do|v|self.verbose =vendendend## Return a structure describing the options.#defparse(args)# The options specified on the command line will be collected in# *options*.@options =ScriptOptions.new@args =OptionParser.newdo|parser|@options.define_options(parser)parser.parse!(args)end@optionsendattr_reader:parser,:optionsend# class OptparseExampleexample =OptparseExample.newoptions =example.parse(ARGV)ppoptions# example.optionsppARGV
ShellCompletion¶↑
For modern shells (e.g. bash, zsh, etc.), you can use shell completion for command line options.
Further documentation¶↑
The above examples, along with the accompanyingTutorial, should be enough to learn how to use this class. If you have any questions, file a ticket atbugs.ruby-lang.org.
Constants
- DecimalInteger
Decimal integer format, to be converted to
Integer.- DecimalNumeric
Decimal integer/float number format, to be converted to
Integerfor integer format,Floatfor float format.- OctalInteger
Ruby/C like octal/hexadecimal/binary integer format, to be converted to
Integer.- VERSION
The version string
- Version
Attributes
Heading banner preceding summary.
Strings to be parsed in default.
Program name to be emitted in error message and default banner, defaults to $0.
Whether to raise at unknown option.
Release code
Whether to require that options match exactly (disallows providing abbreviated long option as short option).
Heading banner preceding summary.
Program name to be emitted in error message and default banner, defaults to $0.
Width for option list portion of summary. Must beNumeric.
Width for option list portion of summary. Must beNumeric.
Public Class Methods
Source
# File lib/optparse.rb, line 1240defself.accept(*args,&blk)top.accept(*args,&blk)end
Seeaccept.
Source
# File lib/optparse.rb, line 1945defself.getopts(*args,symbolize_names:false)new.getopts(*args,symbolize_names:symbolize_names)end
Seegetopts.
Source
# File lib/optparse.rb, line 1162defself.inc(arg,default =nil)caseargwhenIntegerarg.nonzero?whennildefault.to_i+1endend
Returns an incremented value ofdefault according toarg.
Source
# File lib/optparse.rb, line 1185definitialize(banner =nil,width =32,indent =' '*4)@stack = [DefaultList,List.new,List.new]@program_name =nil@banner =banner@summary_width =width@summary_indent =indent@default_argv =ARGV@require_exact =false@raise_unknown =trueadd_officiousyieldselfifblock_given?end
Initializes the instance and yields itself if called with a block.
bannerBanner message.
widthSummary width.
indentSummary indent.
Source
# File lib/optparse.rb, line 1253defself.reject(*args,&blk)top.reject(*args,&blk)end
Seereject.
Source
# File lib/optparse/version.rb, line 10defshow_version(*pkgs)progname =ARGV.options.program_nameresult =falseshow =procdo|klass,cname,version|str ="#{progname}"unlessklass==::Objectandcname==:VERSIONversion =version.join(".")ifArray===versionstr<<": #{klass}"unlessklass==Objectstr<<" version #{version}"end [:Release,:RELEASE].finddo|rel|ifklass.const_defined?(rel)str<<" (#{klass.const_get(rel)})"endendputsstrresult =trueendifpkgs.size==1andpkgs[0]=="all"self.search_const(::Object,/\AV(?:ERSION|ersion)\z/)do|klass,cname,version|unlesscname[1]==?eandklass.const_defined?(:Version)show.call(klass,cname.intern,version)endendelsepkgs.eachdo|pkg|beginpkg =pkg.split(/::|\//).inject(::Object) {|m,c|m.const_get(c)}v =casewhenpkg.const_defined?(:Version)pkg.const_get(n =:Version)whenpkg.const_defined?(:VERSION)pkg.const_get(n =:VERSION)elsen =nil"unknown"endshow.call(pkg,n,v)rescueNameErrorendendendresultend
Shows version string in packages ifVersion is defined.
pkgspackage list
Source
# File lib/optparse.rb, line 1215defself.terminate(arg =nil)throw:terminate,argend
Seeterminate.
Source
# File lib/optparse.rb, line 1225defself.top()DefaultListend
Returns the global top option list.
Do not use directly.
Source
# File lib/optparse.rb, line 1153defself.with(*args,&block)opts =new(*args)opts.instance_eval(&block)optsend
Initializes a new instance and evaluates the optional block in context of the instance. Argumentsargs are passed tonew, see there for description of parameters.
This method isdeprecated, its behavior corresponds to the oldernew method.
Public Instance Methods
Source
# File lib/optparse.rb, line 1363defabort(mesg =$!)super("#{program_name}: #{mesg}")end
Shows message with the program name then aborts.
mesgMessage, defaulted to +$!+.
SeeKernel#abort.
Kernel#abortSource
# File lib/optparse.rb, line 1236defaccept(*args,&blk)top.accept(*args,&blk)end
Directs to accept specified classt. The argument string is passed to the block in which it should be converted to the desired class.
tArgument class specifier, any object including Class.
patPattern for argument, defaults to
tif it responds to match.
accept(t,pat,&block)
Source
# File lib/optparse.rb, line 1996defadditional_message(typ,opt)returnunlesstypandoptanddefined?(DidYouMean::SpellChecker)all_candidates = []visit(:get_candidates,typ)do|candidates|all_candidates.concat(candidates)endall_candidates.select! {|cand|cand.is_a?(String) }checker =DidYouMean::SpellChecker.new(dictionary:all_candidates)DidYouMean.formatter.message_for(all_candidates&checker.correct(opt))end
Returns additional info.
Source
# File lib/optparse.rb, line 1285defbannerunless@banner@banner =+"Usage: #{program_name} [options]"visit(:add_banner,@banner)end@bannerend
Heading banner preceding summary.
Source
# File lib/optparse.rb, line 2010defcandidate(word)list = []casewordwhen'-'long =short =truewhen/\A--/word,arg =word.split(/=/,2)argpat =Completion.regexp(arg,false)ifargand!arg.empty?long =truewhen/\A-/short =trueendpat =Completion.regexp(word,long)visit(:each_option)do|opt|nextunlessSwitch===optopts = (long?opt.long: [])+ (short?opt.short: [])opts =Completion.candidate(word,true,pat,&opts.method(:each)).map(&:first)ifpatif/\A=/=~opt.argopts.map! {|sw|sw+"="}ifargandCompletingHash===opt.patternifopts =opt.pattern.candidate(arg,false,argpat)opts.map!(&:last)endendendlist.concat(opts)endlistend
Return candidates forword.
Source
# File lib/optparse.rb, line 1635defdefine(*opts,&block)top.append(*(sw =make_switch(opts,block)))sw[0]end
Creates an option from the given parametersparams. SeeParameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. SeeOption Handlers.
Source
# File lib/optparse/kwargs.rb, line 15defdefine_by_keywords(options,method,**params)method.parameters.eachdo|type,name|casetypewhen:key,:keyreqop,cl =*(type==:key?%w"[ ]": ["",""])define("--#{name}=#{op}#{name.upcase}#{cl}",*params[name])do|o|options[name] =oendendendoptionsend
Creates an option from the given parametersparams. SeeParameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. SeeOption Handlers.
Defines options which set in tooptions for keyword parameters ofmethod.
Parameters for each keywords are given as elements ofparams.
Source
# File lib/optparse.rb, line 1656defdefine_head(*opts,&block)top.prepend(*(sw =make_switch(opts,block)))sw[0]end
Creates an option from the given parametersparams. SeeParameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. SeeOption Handlers.
Source
# File lib/optparse.rb, line 1679defdefine_tail(*opts,&block)base.append(*(sw =make_switch(opts,block)))sw[0]end
Creates an option from the given parametersparams. SeeParameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. SeeOption Handlers.
Source
# File lib/optparse.rb, line 2091defenvironment(env =File.basename($0,'.*'),**keywords)env =ENV[env]||ENV[env.upcase]orreturnrequire'shellwords'parse(*Shellwords.shellwords(env),**keywords)end
Parses environment variableenv or its uppercase with splitting like a shell.
env defaults to the basename of the program.
Source
# File lib/optparse.rb, line 1907defgetopts(*args,symbolize_names:false,**keywords)argv =Array===args.first?args.shift:default_argvsingle_options,*long_options =*argsresult = {}setter = (symbolize_names?->(name,val) {result[name.to_sym] =val}:->(name,val) {result[name] =val})single_options.scan(/(.)(:)?/)do|opt,val|ifvalsetter[opt,nil]define("-#{opt} VAL")elsesetter[opt,false]define("-#{opt}")endendifsingle_optionslong_options.eachdo|arg|arg,desc =arg.split(';',2)opt,val =arg.split(':',2)ifvalsetter[opt, (valunlessval.empty?)]define("--#{opt}=#{result[opt] || "VAL"}",*[desc].compact)elsesetter[opt,false]define("--#{opt}",*[desc].compact)endendparse_in_order(argv,setter,**keywords)resultend
Wrapper method for getopts.rb.
params =ARGV.getopts("ab:","foo","bar:","zot:Z;zot option")# params["a"] = true # -a# params["b"] = "1" # -b1# params["foo"] = "1" # --foo# params["bar"] = "x" # --bar x# params["zot"] = "z" # --zot Z
Optionsymbolize_names (boolean) specifies whether returnedHash keys should be Symbols; defaults tofalse (use Strings).
params =ARGV.getopts("ab:","foo","bar:","zot:Z;zot option",symbolize_names:true)# params[:a] = true # -a# params[:b] = "1" # -b1# params[:foo] = "1" # --foo# params[:bar] = "x" # --bar x# params[:zot] = "z" # --zot Z
Source
# File lib/optparse.rb, line 1422defhelp;summarize("#{banner}".sub(/\n?\z/,"\n"))end
Returns option summary string.
Source
# File lib/optparse.rb, line 2051defload(filename =nil,**keywords)unlessfilenamebasename =File.basename($0,'.*')returntrueifload(File.expand_path("~/.options/#{basename}"),**keywords)rescuenilbasename<<".options"if!(xdg =ENV['XDG_CONFIG_HOME'])orxdg.empty?# https://specifications.freedesktop.org/basedir-spec/latest/#variables## If $XDG_CONFIG_HOME is either not set or empty, a default# equal to $HOME/.config should be used.xdg = ['~/.config',true]endreturn [xdg,*ENV['XDG_CONFIG_DIRS']&.split(File::PATH_SEPARATOR),# Haiku ['~/config/settings',true], ].any? {|dir,expand|nextif!dirordir.empty?filename =File.join(dir,basename)filename =File.expand_path(filename)ifexpandload(filename,**keywords)rescuenil }endbeginparse(*File.readlines(filename,chomp:true),**keywords)truerescueErrno::ENOENT,Errno::ENOTDIRfalseendend
Loads options from file names asfilename. Does nothing when the file is not present. Returns whether successfully loaded.
filename defaults to basename of the program without suffix in a directory ~/.options, then the basename with ‘.options’ suffix under XDG and Haiku standard places.
The optionalinto keyword argument works exactly like that accepted in methodparse.
Source
# File lib/optparse.rb, line 1477defmake_switch(opts,block =nil)short,long,nolong,style,pattern,conv,not_pattern,not_conv,not_style = [], [], []ldesc,sdesc,desc,arg = [], [], []default_style =Switch::NoArgumentdefault_pattern =nilklass =nilq,a =nilhas_arg =falsevalues =nilopts.eachdo|o|# argument classnextifsearch(:atype,o)do|pat,c|klass =notwice(o,klass,'type')ifnot_styleandnot_style!=Switch::NoArgumentnot_pattern,not_conv =pat,celsedefault_pattern,conv =pat,cendend# directly specified pattern(any object possible to match)if!Completion.completable?(o)ando.respond_to?(:match)pattern =notwice(o,pattern,'pattern')ifpattern.respond_to?(:convert)conv =pattern.method(:convert).to_procelseconv =SPLAT_PROCendnextend# anything otherscaseowhenProc,Methodblock =notwice(o,block,'block')whenArray,Hash,SetifArray===oo,v =o.partition {|v,|Completion.completable?(v)}values =notwice(v,values,'values')unlessv.empty?nextifo.empty?endcasepatternwhenCompletingHashwhennilpattern =CompletingHash.newconv =pattern.method(:convert).to_procifpattern.respond_to?(:convert)elseraiseArgumentError,"argument pattern given twice"endo.each {|pat,*v|pattern[pat] =v.fetch(0) {pat}}whenRangevalues =notwice(o,values,'values')whenModuleraiseArgumentError,"unsupported argument type: #{o}",ParseError.filter_backtrace(caller(4))when*ArgumentStyle.keysstyle =notwice(ArgumentStyle[o],style,'style')when/\A--no-([^\[\]=\s]*)(.+)?/q,a =$1,$2o =notwice(a?Object:TrueClass,klass,'type')not_pattern,not_conv =search(:atype,o)unlessnot_stylenot_style = (not_style||default_style).guess(arg =a)ifadefault_style =Switch::NoArgumentdefault_pattern,conv =search(:atype,FalseClass)unlessdefault_patternldesc<<"--no-#{q}" (q =q.downcase).tr!('_','-')long<<"no-#{q}"nolong<<qwhen/\A--\[no-\]([^\[\]=\s]*)(.+)?/q,a =$1,$2o =notwice(a?Object:TrueClass,klass,'type')ifadefault_style =default_style.guess(arg =a)default_pattern,conv =search(:atype,o)unlessdefault_patternendldesc<<"--[no-]#{q}" (o =q.downcase).tr!('_','-')long<<onot_pattern,not_conv =search(:atype,FalseClass)unlessnot_stylenot_style =Switch::NoArgumentnolong<<"no-#{o}"when/\A--([^\[\]=\s]*)(.+)?/q,a =$1,$2ifao =notwice(NilClass,klass,'type')default_style =default_style.guess(arg =a)default_pattern,conv =search(:atype,o)unlessdefault_patternendldesc<<"--#{q}" (o =q.downcase).tr!('_','-')long<<owhen/\A-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/q,a =$1,$2o =notwice(Object,klass,'type')ifadefault_style =default_style.guess(arg =a)default_pattern,conv =search(:atype,o)unlessdefault_patternelsehas_arg =trueendsdesc<<"-#{q}"short<<Regexp.new(q)when/\A-(.)(.+)?/q,a =$1,$2ifao =notwice(NilClass,klass,'type')default_style =default_style.guess(arg =a)default_pattern,conv =search(:atype,o)unlessdefault_patternendsdesc<<"-#{q}"short<<qwhen/\A=/style =notwice(default_style.guess(arg =o),style,'style')default_pattern,conv =search(:atype,Object)unlessdefault_patternelsedesc.push(o)ifo&&!o.empty?endenddefault_pattern,conv =search(:atype,default_style.pattern)unlessdefault_patternifRange===valuesandklassunless (!values.beginorklass===values.begin)and (!values.endorklass===values.end)raiseArgumentError,"range does not match class"endendif!(short.empty?andlong.empty?)ifhas_arganddefault_style==Switch::NoArgumentdefault_style =Switch::RequiredArgumentends = (style||default_style).new(pattern||default_pattern,conv,sdesc,ldesc,arg,desc,block,values)elsif!blockifstyleorpatternraiseArgumentError,"no switch given",ParseError.filter_backtrace(caller)ends =descelseshort<<patterns = (style||default_style).new(pattern,conv,nil,nil,arg,desc,block,values)endreturns,short,long, (not_style.new(not_pattern,not_conv,sdesc,ldesc,nil,desc,block)ifnot_style),nolongend
Creates an option from the given parametersparams. SeeParameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. SeeOption Handlers.
Source
# File lib/optparse.rb, line 1387defnew@stack.push(List.new)ifblock_given?yieldselfelseselfendend
Pushes a newList.
If a block is given, yieldsself and returns the result of the block, otherwise returnsself.
Source
# File lib/optparse.rb, line 1645defon(*opts,&block)define(*opts,&block)selfend
Creates an option from the given parametersparams. SeeParameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. SeeOption Handlers.
Source
# File lib/optparse.rb, line 1668defon_head(*opts,&block)define_head(*opts,&block)selfend
Creates an option from the given parametersparams. SeeParameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. SeeOption Handlers.
The new option is added at the head of the summary.
Source
# File lib/optparse.rb, line 1692defon_tail(*opts,&block)define_tail(*opts,&block)selfend
Creates an option from the given parametersparams. SeeParameters for New Options.
The block, if given, is the handler for the created option. When the option is encountered during command-line parsing, the block is called with the argument given for the option, if any. SeeOption Handlers.
The new option is added at the tail of the summary.
Source
# File lib/optparse.rb, line 1721deforder(*argv,**keywords,&nonopt)argv =argv[0].dupifargv.size==1andArray===argv[0]order!(argv,**keywords,&nonopt)end
Parses command line argumentsargv in order. When a block is given, each non-option argument is yielded. When optionalinto keyword argument is provided, the parsed option values are stored there via[]= method (so it can beHash, orOpenStruct, or other similar object).
Returns the rest ofargv left unparsed.
Source
# File lib/optparse.rb, line 1730deforder!(argv =default_argv,into:nil,**keywords,&nonopt)setter =->(name,val) {into[name.to_sym] =val}ifintoparse_in_order(argv,setter,**keywords,&nonopt)end
Same asorder, but removes switches destructively. Non-option arguments remain inargv.
Source
# File lib/optparse.rb, line 1871defparse(*argv,**keywords)argv =argv[0].dupifargv.size==1andArray===argv[0]parse!(argv,**keywords)end
Parses command line argumentsargv in order when environment variable POSIXLY_CORRECT is set, and in permutation mode otherwise. When optionalinto keyword argument is provided, the parsed option values are stored there via[]= method (so it can beHash, orOpenStruct, or other similar object).
Source
# File lib/optparse.rb, line 1880defparse!(argv =default_argv,**keywords)ifENV.include?('POSIXLY_CORRECT')order!(argv,**keywords)elsepermute!(argv,**keywords)endend
Same asparse, but removes switches destructively. Non-option arguments remain inargv.
Source
# File lib/optparse.rb, line 1848defpermute(*argv,**keywords)argv =argv[0].dupifargv.size==1andArray===argv[0]permute!(argv,**keywords)end
Parses command line argumentsargv in permutation mode and returns list of non-option arguments. When optionalinto keyword argument is provided, the parsed option values are stored there via[]= method (so it can beHash, orOpenStruct, or other similar object).
Source
# File lib/optparse.rb, line 1857defpermute!(argv =default_argv,**keywords)nonopts = []order!(argv,**keywords) {|nonopt|nonopts<<nonopt}argv[0,0] =nonoptsargvend
Same aspermute, but removes switches destructively. Non-option arguments remain inargv.
Source
# File lib/optparse.rb, line 1297defprogram_name@program_name||strip_ext(File.basename($0))end
Program name to be emitted in error message and default banner, defaults to $0.
Source
# File lib/optparse.rb, line 1249defreject(*args,&blk)top.reject(*args,&blk)end
Directs to reject specified class argument.
typeArgument class specifier, any object including Class.
reject(type)
Source
# File lib/optparse.rb, line 1330defrelease (defined?(@release)&&@release)|| (defined?(::Release)&&::Release)|| (defined?(::RELEASE)&&::RELEASE)end
Release code
Source
# File lib/optparse.rb, line 1701defseparator(string)top.append(string,nil,nil)end
Add separator in summary.
Source
# File lib/optparse.rb, line 1412defsummarize(to = [],width =@summary_width,max =width-1,indent =@summary_indent,&blk)nl ="\n"blk||=proc {|l|to<< (l.index(nl,-1)?l:l+nl)}visit(:summarize, {}, {},width,max,indent,&blk)toend
Puts option summary intoto and returnsto. Yields each line if a block is given.
toOutput destination, which must have method <<. Defaults to [].
widthWidth of left side, defaults to @summary_width.
maxMaximum length allowed for left side, defaults to
width- 1.indentIndentation, defaults to @summary_indent.
Source
# File lib/optparse.rb, line 1209defterminate(arg =nil)self.class.terminate(arg)end
Terminates option parsing. Optional parameterarg is a string pushed back to be the first non-option argument.
Source
# File lib/optparse.rb, line 1451defto_a;summarize("#{banner}".split(/^/))end
Returns option summary list.
Source
# File lib/optparse.rb, line 1337defverifv =versionstr =+"#{program_name} #{[v].join('.')}"str<<" (#{v})"ifv =releasestrendend
Returns version string fromprogram_name, version and release.
Source
# File lib/optparse.rb, line 1323defversion (defined?(@version)&&@version)|| (defined?(::Version)&&::Version)end
Source
# File lib/optparse.rb, line 1352defwarn(mesg =$!)super("#{program_name}: #{mesg}")end
Shows warning message with the program name
mesgMessage, defaulted to +$!+.
SeeKernel#warn.
Kernel#warn