在Ruby中使用OptionParse强制使用命令行参数

3

I have this code:

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 参数时显示的那样。
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!

还有一种非破坏性的解析,但如果您计划使用ARGV中剩余的内容,则它不太有用。

OptionParser类没有强制执行必填参数(例如此处的--site)的方法。但是,在运行parse!后,您可以自行检查:

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

如果需要更通用的强制选项处理程序,请参见此答案。如果不清楚的话,除非你特意使它们成为强制选项,否则所有选项都是可选的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接