rubyoptionparser

I have three flags in OptionParser but it only gives access to two of them


I am building a CLI gem with Ruby and I'm using OptionParser to add flags with arguments. Whenever one flag is called with an argument a function get's called. I have three flags. My problem is, when I run the -h command to see the options(flags) available to use, it only shows three of them (skipping the middle one) and even if I try to use that flag, (that is not listed in help) it runs the code of the last flag. Here is my code for the flags:

def city_weather
      options = {}
      OptionParser.new do |opts|
        opts.banner = "Welcome to El Tiempo! \n Usage: cli [options]"

        opts.on('-today', 'Get today\'s weather') do |today|
          options[:today] = today
          weather_today(ARGV.first)
        end

        opts.on('-av_max', 'Get this week\'s average maximum temperature') do |av_max|
          options[:av_max] = av_max
          week_average_max(ARGV.first)
        end

        opts.on('-av_min', 'Get this week\'s average minimum temperature') do |av_min|
          options[:av_min] = av_min
          week_average_min(ARGV.first)
        end
      end.parse!

      ARGV.first
    end

It is the -av_max flag that does not work. When I run -av_max the week_average_min(ARGV.first) get's executed.

When I run the -h command here is what it shows:

Welcome to El Tiempo! 
Usage: cli [options]
    -today                           Get today's weather
    -av_min                          Get this week's average minimum temperature

My question is, is it possible to have three flags with OptionParser? If so, how could I make this middle flat work?


Solution

  • You need to add another dash for long arguments:

    opts.on('--av_min', 'Get this week\'s average minimum temperature') do |av_min|
      options[:av_min] = av_min
      week_average_min(ARGV.first)
    end