有趣的行为是,如果您定义以相同字母开头的相似长选项,在示例中是s
. 它不允许使用-s
key with exception OptionParser::AmbiguousOption
,但似乎没有办法在OptionParser
不侵入其代码的情况下禁用 short 选项:
#! /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。按如下方式使用它:
宝石文件
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
模拟:
$ 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"}