2012-10-15 93 views
0
require 'optparse' 
params = ARGV.getopts("a:", "AA") 

ruby a.rb -a顯示:如何在ruby中更改optparse的默認錯誤信息?

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

ruby a.rb -b顯示:

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

我想表明我的幫助信息,我該怎麼做呢?

回答

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 
... 
相關問題