How to get only long functions in OptionParser in Ruby?

I have such simple code in Ruby (test.rb):

#! /usr/bin/env ruby

require 'optparse'

OptionParser.new do |option|
  option.on("--sort", "Sort data") do 
    puts "--sort passed"
  end
end.parse!

then I ran it: ./test.rb -sand got:

--sort passed

Did I miss something?

I want to use only the --sort(long) option, not the short one.

How do i get it?

+4
source share
4 answers

I found the code that causes this behavior, in optparse.rblines 1378-1380:

# if no short options match, try completion with long
# options.
sw, = complete(:long, opt)

If you don’t like this behavior, it seems your best option is to create a copy optparse.rbin your project, delete the offensive sentence rescue InvalidOptioninside the copy and loadnot the standard version of the library.

+2
source

, , , s. -s OptionParser::AmbiguousOption, , OptionParser :

#! /usr/bin/env ruby

require 'optparse'

OptionParser.new do |option|
  option.on("--sport", "Sport data") do
    puts "--sport passed"
  end
  option.on("--sort", "Sort data") do
    puts "--sort passed"
  end
end.parse!

on:

OptionParser.new do |option|
  opts = [ "--sort", "Sort data" ]
  sw = option.make_switch(opts) 
  block = proc { puts "--sort passed" }
  sw[0].instance_variable_set :@block, block
  option.top.append *sw
  p sw
  # => [#<OptionParser::Switch::NoArgument:0x806c770 @pattern=/.*/m, @conv=#<Proc:0x806dd8c@/home/malo/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/optparse.rb:1617>, @short=[], @long=["--sort"], @arg=nil, @desc=["Sort data"], @block=#<Proc:0x806c70c@./1.rb:8>>, [], ["sort"], nil, []]
end.parse!
# => --sort passed when  ./1.rb --sort and ./1.rb -s

, @short , -s.

micro-optparse gem. :

Gemfile

gem 'micro-optparse', :git => 'https://github.com/3aHyga/micro-optparse.git', :branch => 'no-short' # for now it is available only from git repo

ruby_script.rb

require 'micro-optparse'

options = Parser.new do |p|
   p.banner = "This is a fancy script, for usage see below"
   p.option :sport, "sport", :default => "Sport", :short => "p"
   p.option :sort, "sort", :default => "Sort", :short => false
end.process!

p options

Simulation:

$ bundle exec ./1.rb --sort 111
{:sport=>"Sport", :sort=>"111"}

$ bundle exec ./1.rb -s 111
ambiguous option: -s

$ bundle exec ./1.rb -p 111
{:sport=>"111", :sort=>"Sort"}
+2

"--sort", , "-s", "s", "+ s" ..

:

require 'optparse'

OptionParser.new do |option|
  option.on("--sort TYPE", %w(-s s +s), "Sort data") do |type|
    puts "--sort passed with argument #{type}"
  end
end.parse!

:

$ ./test.rb --sort -s
--sort passed with argument -s
$ ./test.rb --sort s
--sort passed with argument s
$ ./test.rb --sort +s
--sort passed with argument +s

, -s:

$ ./test.rb -s -s
--sort passed with argument -s
$ ./test.rb -s s
--sort passed with argument s
$ ./test.rb -s +s
--sort passed with argument +s
+1

, .

#on #make_switch, . .

, ? , , .

, (, highline, slop, trollop) .

0

All Articles