How does Ruby's OptionParser work? -
"minimal example" of optionparser http://ruby-doc.org/stdlib-2.1.5/libdoc/optparse/rdoc/optionparser.html:
require 'optparse' options = {} optionparser.new |opts| opts.banner = "usage: example.rb [options]" opts.on("-v", "--[no-]verbose", "run verbosely") |v| options[:verbose] = v end end.parse! p options p argv main questions:
- what content of
optsthere? new optionparser instance, or of/-\w/or/--\w+/-looking things passed script? corollary,doblock loop or not? - what
parse!do? why called on wholedoblock?
also wondering:
- what
optionparser#bannermethod? in context see text? - in context see third parameter passed optionparser in example, little description of flag's effect?
- how can create custom error message if script run unknown option?
optsnew instance ofoptionparser. block supplied.newrun line:yield self if block_given?parse!same thingparsedestructive, meaning remove used switchesargv. called on entiredo ... endblock because value returned newoptionparserinstance.bannergets heading of summary, can setopts.banner = "foo"the description shown when displayed (
-hflag):usage: example.rb [options] -v, --[no-]verbose run verboselyyou rescue
optionparser::invalidoptionexception:parser = optionparser.new ... begin parser.parse! rescue optionparser::invalidoption puts 'invalid args!' end
Comments
Post a Comment