0

optparseを使用してコマンドラインオプションを取り込む方法を学習しようとしていますが、クラスのドキュメントやオンラインで見つけることができる例に示されているように、optparseを機能させるのに苦労しています。具体的には、-hオプションを渡すと、何も表示されません。ARGVと、-hを受信したことを示す出力を出力できますが、opts.bannerやoptsのいずれかが表示されません。ここで何が欠けていますか?

class TestThing

def self.parse(args)
    options = {}
        options[:time]        = 0
        options[:operation]   = :add
        options[:input_file]  = ARGV[-2]
        options[:output_file] = ARGV[-1]
            optparse = OptionParser.new do |opts|
                opts.banner = "Usage:[OPTIONS] input_file output_file"

                opts.separator = ""
                opts.separator = "Specific Options:"


                opts.on('-o', '--operation [OPERATION]', "Add or Subtract time, use 'add' or 'sub'") do |operation|
                    optopns[:operation] = operation.to_sym
                end

                opts.on('-t', '--time [TIME]', "Time to be shifted, in milliseconds") do |time|
                    options[:time] = time
                end

                opts.on_tail("-h", "--help", "Display help screen") do
                    puts opts
                    exit
                end

                opt_parser.parse!(args)
                options
            end
end
end
4

1 に答える 1

0

の結果を保持してからOptionParser.new呼び出す必要がありparse!ます。

op = OptionParser.new do
  # what you have now
end

op.parse!

new次のように、に与えるブロックの外側でこれを行う必要があることに注意してください。

class TestThing

def self.parse(args)
    options = {}
        options[:time]        = 0
        options[:operation]   = :add
        options[:input_file]  = ARGV[-2]
        options[:output_file] = ARGV[-1]
            optparse = OptionParser.new do |opts|
                opts.banner = "Usage:[OPTIONS] input_file output_file"
                # all the rest of your app
            end
            optparse.parse!(args)
end
end

(意味を明確にするためにインデントを残しましたが、一貫してインデントすると、コードが扱いやすくなります)。

また、追加する必要はありません-h---helpこれらOptionParserは自動的に提供され、実装したとおりに実行されます。

于 2013-03-24T12:12:32.013 に答える