2013-12-16 38 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