"Minimal example" of OptionParser from http://ruby-doc.org/stdlib-2.1.5/libdoc/optparse/rdoc/OptionParser.html:
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
end.parse!
p options
p ARGV
Main questions:
- What exactly is the content of
optsthere? Is it the new OptionParser instance, or is it all of the/-\w/or/--\w+/-looking things passed to the script? As a corollary, is thatdoblock a loop or not? - What does
parse!do? Why is it called on the wholedoblock?
Also wondering:
- What is the
OptionParser#bannermethod? In what context would you see that text? - In what context would you see the third parameter passed to OptionParser in that example, that little description of the flag's effect?
- How can you create a custom error message if the script is run with an unknown option?
optsis just the new instance ofOptionParser. The block supplied to.newis run with this line:parse!is the same thing asparsebut it is destructive, meaning that it will remove used switches fromARGV. It is called on the entiredo ... endblock because the value returned is the newOptionParserinstance.bannergets the heading of the summary, which can be set withopts.banner = "foo"The description is shown when the help is displayed (
-hflag):You could rescue the
OptionParser::InvalidOptionexception: