"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
opts
there? 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 thatdo
block a loop or not? - What does
parse!
do? Why is it called on the wholedo
block?
Also wondering:
- What is the
OptionParser#banner
method? 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?
opts
is just the new instance ofOptionParser
. The block supplied to.new
is run with this line:parse!
is the same thing asparse
but it is destructive, meaning that it will remove used switches fromARGV
. It is called on the entiredo ... end
block because the value returned is the newOptionParser
instance.banner
gets the heading of the summary, which can be set withopts.banner = "foo"
The description is shown when the help is displayed (
-h
flag):You could rescue the
OptionParser::InvalidOption
exception: