2013-03-20 52 views
0

我想學習如何使用optparse接受命令行選項,但是我很難讓它的功能,因爲它顯示在類文檔和任何我能找到的例子線上。特別是當我通過-h選項時沒有任何東西出現。我可以輸出ARGV並顯示它收到-h但它不會顯示opts.banner和/或任何opts。我在這裏錯過了什麼?無法獲得紅寶石optparse輸出選擇

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 

回答

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 

(我離開你的縮進,使之更清晰了我的意思,但在一個側面說明,你會發現代碼更容易,如果你縮進利弊工作istently)。

另外,您不需要添加-h--help - OptionParser會自動爲您提供這些功能,並且完全按照您實施它們的方式執行。

+0

我已經在第8行和第5行從底部,我沒有實現這個不正確? – 2013-04-04 05:43:13

+0

你需要在你給新的區塊之外打電話 - 更新我的答案以顯示我的意思(希望) – davetron5000 2013-04-04 13:26:23