3

我有这个代码:

options = {}
opt_parse = OptionParser.new do |opts|
  opts.banner = "Usage: example.rb [options]"

  opts.on("-g", "--grade [N]", "Grade") do |g|
    options[:grade] = g
  end

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end

end
opt_parse.parse!

如何强制设置-g参数?如果未指定,则触发使用消息,如-h调用参数时所示。

4

1 回答 1

3

OptionParser 没有检查强制选项的内置方法。但是解析后很容易检查:

if options[:grade].nil?
  abort(opt_parse.help)
end

如果您不寻找任何太复杂的东西,手动解析命令行相对容易:

# Naive error checking
abort('Usage: ' + $0 + ' site id ...') unless ARGV.length >= 2

# First item (site) is mandatory
site = ARGV.shift

ARGV.each do | id |
  # Do something interesting with each of the ids
end

但是当您的选项开始变得更加复杂时,您可能需要使用选项解析器,例如OptionParser

require 'optparse'

# The actual options will be stored in this hash
options = {}

# Set up the options you are looking for
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} -s NAME id ..."

  opts.on("-s", "--site NAME", "Site name") do |s|
    options[:site] = s
  end

  opts.on( '-h', '--help', 'Display this screen' ) do
    puts opts
    exit
  end
end

# The parse! method also removes any options it finds from ARGV.
optparse.parse!

还有一个非破坏性的parse,但如果您打算使用ARGV.

OptionParser 类没有强制执行强制参数的方法(例如--site在这种情况下)。但是,您可以在运行后自行检查parse!

# Slightly more sophisticated error checking
if options[:site].nil? or ARGV.length == 0
  abort(optparse.help)
end

有关更通用的强制选项处理程序,请参阅此答案。如果不清楚,所有选项都是可选的,除非您竭尽全力将它们设为强制性。

于 2017-05-02T00:39:32.153 回答