Alina
Alina

Reputation: 2261

Ruby OptionParser does not set a parameter

This is my parser:

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

after I run the code with ruby main.rb -t 'w' -w 'wr1707' the options are following:

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

For some reason options[:time] is not set and I do not understand why. Is there maybe some problem with conversions, that I am not allowed to use -t as a parameter?

Upvotes: 1

Views: 45

Answers (1)

lcguida
lcguida

Reputation: 3847

When expecting arguments, you should tell OptionParser which argument and if it's optional or obligatory, see documentation:

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

So in your case, for the time option, description should be like this:

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

or like this, if you want to do it optional:

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

Upvotes: 1

Related Questions