下面的代码可以工作,但是当我想要为必需的参数构建必需参数到本机的OptionParser sytax时,我手动提取使用fetch所需参数的参数错误:
# ocra script.rb -- --type=value options = {} OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("--type [TYPE]",String,[:gl,:time],"Select Exception file type (gl,time)") do |t| options["type"] = t end opts.on("--company [TYPE]",[:jaxon,:doric],"Select Company (jaxon,doric)") do |t| options["company"] = t end end.parse! opts = {} opts['type'] = options.fetch('type') do raise ArgumentError,"no 'type' option specified as a parameter (gl or time)" end opts['company'] = options.fetch('company') do raise ArgumentError,"no 'company' option specified as a parameter (doric or jaxon)" end
解决方法
有一个类似的问题,答案可能会帮助你:
“ How do you specify a required switch (not argument) with Ruby OptionParser?”
“ How do you specify a required switch (not argument) with Ruby OptionParser?”
简而言之:似乎没有办法选择需要的(毕竟它们被称为选项).
有一个OptionParser :: MissingArgument异常,您可以加注,而不是您当前抛出的ArgumentError.