Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are long option names case insensitive using OptionParser?

Tags:

ruby

optparse

In the following script, the short options work as expected, the long ones don't:

#!/usr/bin/env ruby
require 'optparse'

optparse = OptionParser.new do|opts|
   opts.on( '-h', '--help', 'Display standard help') do puts opts    end
   opts.on( '-H', '--Help', 'Display other help'   ) do puts 'Help!' end
end
optparse.parse!

Here are the results when running it:

$ ./test -h
Usage: t [options]
-h, --help                       Display standard help
-H, --Help                       Display other help
$ ./test -H
Help!
$ ./test --help
Help!
$ ./test --Help
Help!

Is there a way to have --help generate the same output as -h?

like image 861
Wybo Dekker Avatar asked Apr 23 '26 11:04

Wybo Dekker


2 Answers

Yes, it seems that long options are case-insensitive. This is by convention, I imagine. Never seen a tool with case-sensitive long names.

See the source: https://github.com/ruby/ruby/blob/b4974e71dcb32d430d7d686c5de247218991ec6c/lib/optparse.rb#L1408

You can copy and modify source of OptionParser, but you probably should not do this. :)

like image 130
Sergio Tulentsev Avatar answered Apr 25 '26 00:04

Sergio Tulentsev


Starting with:

require 'optparse'

options = {}
OptionParser.new do|opts|
  opts.on( '-f', '--foo', 'Display standard help') { |o| options[:foo] = o }
  opts.on( '-F', '--FOO', 'Display other help'   ) { |o| options[:FOO] = o }
end.parse!

puts options

These examples might help make it easier to understand:

OptionParser has -h and --help already defined:

$ ruby test.rb -h
Usage: test [options]
    -f, --foo                        Display standard help
    -F, --Foo                        Display other help

$ ruby test.rb --help
Usage: test [options]
    -f, --foo                        Display standard help
    -F, --Foo                        Display other help

-H isn't defined, so you could use it as a case-sensitive option for extended or secondary help:

$ ruby test.rb -H
test.rb:7:in `<main>': invalid option: -H (OptionParser::InvalidOption)

Single letter, "short flags" are case-sensitive, as we saw with -H:

$ ruby test.rb -f
{:foo=>true}
$ ruby test.rb -F
{:FOO=>true}

And long flags are not case-sensitive:

$ ruby test.rb --foo
{:FOO=>true}
$ ruby test.rb --FOO
{:FOO=>true}
like image 44
the Tin Man Avatar answered Apr 25 '26 01:04

the Tin Man