0
require 'optparse'
params = ARGV.getopts("a:", "AA")  

ruby a.rb -a显示:

a.rb:3:in `<main>': missing argument: -a (OptionParser::MissingArgument)

ruby a.rb -b显示:

a.rb:3:in `<main>': invalid option: -b (OptionParser::InvalidOption)

我想显示我的帮助信息,我该怎么做?

4

1 回答 1

0

实际上,您可以在 OptionParser.new 的块中使用on_tail

但是由于您只是尝试使用 ARGV.getopts,因此显示您自己的帮助消息的技巧将拯救异常:

require 'optparse'

help_msg = <<EOM
This is help message:
Hello buddy, you may do something wrong
...
EOM

begin
  params = ARGV.getopts("a:", "AA")
rescue => e
  puts e.message
  puts '=' * 80
  puts help_msg
end

输出:

ruby a.rb -a
#=>
missing argument: -a
================================================================================
This is help message:
Hello buddy, you may do something wrong
...

ruby a.rb -b
#=>
invalid option: -b
================================================================================
This is help message:
Hello buddy, you may do something wrong
...
于 2012-10-15T08:19:12.487 回答