2013-12-16 42 views
12

我在使用OptionParser和Ruby。沒有參數的OptionParse顯示橫幅

其他語言如C,Python等,有類似的命令行參數解析器,並且它們通常提供了一種在沒有提供參數或參數錯誤時顯示幫助消息的方式。

options = {} 
OptionParser.new do |opts| 
    opts.banner = "Usage: calc.rb [options]" 

    opts.on("-l", "--length L", Integer, "Length") { |l| options[:length] = l } 
    opts.on("-w", "--width W", Integer, "Width") { |w| options[:width] = w } 

    opts.on_tail("-h", "--help", "Show this message") do 
    puts opts 
    exit 
    end 
end.parse! 

問題

  1. 有沒有一種方法來設置默認顯示help消息,如果沒有參數進行傳遞(ruby calc.rb)?
  2. 如果沒有給出所需的參數或者無效,那麼怎麼辦?假設length是一個REQUIRED參數,用戶不會通過它或傳遞錯誤,如-l FOO
+7

補充一點:'ARGV.push( ' - H'),如果ARGV .empty?'解析之前 –

+0

@МалъСкрылевъ,是的,謝謝! – Israel

+0

我的回答有幫助嗎? =) –

回答

23

你可以做這樣的事情:

require 'optparse' 

ARGV << '-h' if ARGV.empty? 

options = {} 
OptionParser.new do |opts| 
    opts.banner = "Usage: calc.rb [options]" 

    opts.on("-l", "--length L", Integer, "Length") { |l| options[:length] = l } 
    opts.on("-w", "--width W", Integer, "Width") { |w| options[:width] = w } 

    opts.on_tail("-h", "--help", "Show this message") do 
    puts opts 
    exit 
    end 
end.parse! 
-1
  1. 您可以在解析之前檢查ARGV(如上答案):
    ARGV << '-h' if ARGV.empty?

    或檢查你的選擇哈希解析後:

    if @options.empty? 
        puts optparse.help 
        puts 'At least 1 argument should be supplied!' 
    end 
    
  2. 這是我做什麼,以確保與OptionParse強制性ARGS(找不到這方面的任何內置功能):

    begin 
        optparse.parse! 
        mandatory = [:length, :width]           # Enforce the presence of 
        missing = mandatory.select{ |param| @options[param].nil? }   # mandatory switches: :length, :width 
        if not missing.empty?             # 
         puts "Missing options: #{missing.join(', ')}"     # 
         puts optparse.help            # 
         exit 2               # 
        end                 # 
    rescue OptionParser::InvalidOption, OptionParser::MissingArgument => error  # 
        puts error                 # Friendly output when parsing fails 
        puts optparse                # 
        exit 2                  # 
    end