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 opts there? new optionparser instance, or of /-\w/ or /--\w+/-looking things passed script? corollary, do block loop or not?
  • what parse! do? why called on whole do block?

also wondering:

  • what optionparser#banner method? 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?

  1. opts new instance of optionparser. block supplied .new run line:

    yield self if block_given? 
  2. parse! same thing parse destructive, meaning remove used switches argv. called on entire do ... end block because value returned new optionparser instance.

  3. banner gets heading of summary, can set opts.banner = "foo"

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

    usage: example.rb [options]     -v, --[no-]verbose               run verbosely 
  5. you rescue optionparser::invalidoption exception:

    parser = optionparser.new ...  begin   parser.parse! rescue optionparser::invalidoption   puts 'invalid args!' end            

Comments

Popular posts from this blog

c++ - OpenMP unpredictable overhead -

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

javascript - Wordpress slider, not displayed 100% width -