Ruby OptionParser不设置参数

时间:2017-02-21 10:25:23

标签: ruby

这是我的解析器:

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 个答案:

答案 0 :(得分: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 }