2017-02-21 34 views
1

這是我的解析器:紅寶石OptionParser不設置參數

options = { frames: 12, showcurrent: false} 
optparse = OptionParser.new do |opts| 
    opts.banner = "Usage: example.rb [options]" 
    opts.on("-f", "--frames", "Only tickets of the last x time frames (default: 12)", Integer) { |v| options[:frames] = v } 
    opts.on("-c", "--show_current", "Show current (false (default) ot true)") { |v| options[:showcurrent] = v } 
    opts.on("-t", "--time", "Type of the report (day, week (default), month, quarter, year)", String) { |v| options[:time] = v } 
    opts.on("-w", "--year_week YEAR-WEEK", "wrYYWW (wr1707)", String) { |v| options[:yw] = v } 
end 
optparse.parse! 
puts options 

後我運行ruby main.rb -t 'w' -w 'wr1707'選項的代碼如下:

{:frames=>12, :showcurrent=>false, :time=>nil, :yw=>"wr1707"} 

出於某種原因,選項[:時間]沒有設置,我不明白爲什麼。是否可能存在轉換問題,我不允許使用-t作爲參數?

回答

1

當期待的參數,你應該告訴OptionParser哪個參數,如果它是可選的還是強制性的,看到documentation

"--switch=MANDATORY" or "--switch MANDATORY" 
"--switch[=OPTIONAL]" 
"--switch" 

所以你的情況,爲time選項,說明應該是這樣的:

opts.on("-t", "--time TIME", "Type of the report (day, week (default), month, quarter, year)", String) { |v| options[:time] = v } 

或類似這樣的,如果你想這樣做可選:

opts.on("-t", "--time [TIME]", "Type of the report (day, week (default), month, quarter, year)", String) { |v| options[:time] = v }