Project

General

Profile

Actions

Bug #17821

closed

Impossible to define only short versions of options in OptionParser

Added by fidalgo (Paulo Fidalgo) over 3 years ago. Updated over 3 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.0.1p64 (2021-04-05 revision 0fb782ee38) [x86_64-linux]
[ruby-core:103566]

Description

I have tried several approaches and either I'm being misled by the documentation or there's a bug.
I've tried this with two versions of ruby 2.7.2 and 3.0.1, both compiled using rbenv.

Here is the code:

require 'optparse'
options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: #{$PROGRAM_NAME} [options]"

  opts.on('-na', 'Numbers for the first column') { |o| options[:na] = o }
  opts.on('-sa', 'Stars for the first column') { |o| options[:sa] = o }

  opts.on('-nb', 'Numbers for the first column') { |o| options[:nb] = o }
  opts.on('-sb', 'Stars for the first column') { |o| options[:sb] = o }

  if ARGV.empty?
    puts opts.help
    exit 1
  end
end.parse!(into: options)

p options

and the output:

ruby options.rb 
Usage: options.rb [options]
    -nb                              Numbers for the first column
    -sb                              Stars for the first column

The bug happens because we should have four different options on the help.

Updated by xtkoba (Tee KOBAYASHI) over 3 years ago

This is because the notation -na is interpreted as a short style switch -n with a mandatory argument a, and overwritten with -nb which is also a short style switch -n.

See https://docs.ruby-lang.org/en/3.0.0/OptionParser.html

Actions #2

Updated by jeremyevans0 (Jeremy Evans) over 3 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0