实际上,您可以在 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
...