Search code examples
rubyoptionparser

Suppress short arguments with OptionParser


I have a Ruby app with a relatively broad set of command-line arguments. I would like to suppress "short" variants for a number of options so that they can only be used in the long ("double dash") form.

Can I somehow suppress short dash variants for some options?

UPDATE 2013/10/08

It turned out that indeed omitting the short variant works! However, for me it didn't because for some reason in my program all the short keys were prefixed with a space. So a simple case like this:

require 'optparse'

op = OptionParser.new
op.on(" -f", "--from FORMAT", "Use the specific format") {}
op.on("--flip", "Do a flip") {}
op.parse!

caused the exception:

ruby why.rb -f some-foos
why.rb:17:in `<main>': ambiguous option: -f (OptionParser::AmbiguousOption

while the advice given (note the lack of space after the opening quote):

require 'optparse'

OptionParser.new do |opts|
  opts.on("-d", "--ding DING", "Should not conflict with dangerous-option") do
    puts "ding set!"
  end
  opts.on("--dangerous-option", "Set dangerous option") do |v|
    puts "dangerous option set to #{v}"
  end
end.parse!

works fine.

$ruby dang.rb -d xyz
ding set!

So thanks p11y for pointing me in the right direction with a working example. Also, if this "leading space" is in place, optparse will not complain - but it will change the interpretation of your short keys (or, better to say, will ignore them and show them as part of your help line! - and still use the auto-generated keys instead).


Solution

  • Just drop the short form:

    require 'optparse'
    
    OptionParser.new do |opts|
      opts.on("--dangerous-option", "Set dangerous option") do |v|
        puts "dangerous option set to #{v}"
      end
    end.parse!
    

     

    $ ruby foo.rb -h
    Usage: foo [options]
            --dangerous-option           Set dangerous option
    
    $ ruby foo.rb --dangerous-option
    dangerous option set to true