How does Ruby's OptionParser work?

567 views Asked by At

"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 that do block a loop or not?
  • What does parse! do? Why is it called on the whole do 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?
1

There are 1 answers

2
August On
  1. opts is just the new instance of OptionParser. The block supplied to .new is run with this line:

    yield self if block_given?
    
  2. parse! is the same thing as parse but it is destructive, meaning that it will remove used switches from ARGV. It is called on the entire do ... end block because the value returned is the new OptionParser instance.

  3. banner gets the heading of the summary, which can be set with opts.banner = "foo"

  4. The description is shown when the help is displayed (-h flag):

    Usage: example.rb [options]
        -v, --[no-]verbose               Run verbosely
    
  5. You could rescue the OptionParser::InvalidOption exception:

    parser = OptionParser.new ...
    
    begin
      parser.parse!
    rescue OptionParser::InvalidOption
      puts 'Invalid args!'
    end