22

OptionParserRubyで使用しています。

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. 必要なパラメーターが指定されていないか無効な場合はどうなりますか? がREQUIREDlengthパラメータであり、ユーザーがそれを渡さないか、次のような間違ったものを渡したとし-l FOOます。
4

3 に答える 3

45

ARGVが空のときに-hキーを追加するだけなので、次のようにすることができます。

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!
于 2013-12-16T06:35:11.160 に答える
-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 で必須の引数を確保するために私が行うことです (このための組み込み機能が見つかりませんでした):

    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     
    
于 2016-03-30T08:35:10.233 に答える