ruby - 如何使用 Ruby OptionParser 指定所需的开关(不是参数)?

标签 ruby arguments optionparser

我正在编写一个脚本,我想要一个带有值的 --host 开关,但是如果没有指定 --host 开关,我想要选项解析失败。

我似乎不知道该怎么做。文档似乎只指定如何使参数值成为强制性的,而不是开关本身。

最佳答案

一种使用 optparse 的方法,可以在缺少开关时提供友好的输出:

#!/usr/bin/env ruby
require 'optparse'

options = {}

optparse = OptionParser.new do |opts|
  opts.on('-f', '--from SENDER', 'username of sender') do |sender|
    options[:from] = sender
  end

  opts.on('-t', '--to RECIPIENTS', 'comma separated list of recipients') do |recipients|
    options[:to] = recipients
  end

  options[:number_of_files] = 1
  opts.on('-n', '--num_files NUMBER', Integer, "number of files to send (default #{options[:number_of_files]})") do |number_of_files|
    options[:number_of_files] = number_of_files
  end

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

begin
  optparse.parse!
  mandatory = [:from, :to]                                         # Enforce the presence of
  missing = mandatory.select{ |param| options[param].nil? }        # the -t and -f switches
  unless missing.empty?                                            #
    raise OptionParser::MissingArgument.new(missing.join(', '))    #
  end                                                              #
rescue OptionParser::InvalidOption, OptionParser::MissingArgument      #
  puts $!.to_s                                                           # Friendly output when parsing fails
  puts optparse                                                          #
  exit                                                                   #
end                                                                      #

puts "Performing task with options: #{options.inspect}"

在没有 -t-f 开关的情况下运行会显示以下输出:

Missing options: from, to
Usage: test_script [options]
    -f, --from SENDER                username of sender
    -t, --to RECIPIENTS              comma separated list of recipients
    -n, --num_files NUMBER           number of files to send (default 1)
    -h, --help

在 begin/rescue 子句中运行 parse 方法允许在其他失败时进行友好格式化,例如缺少参数或无效开关值,例如,尝试为 -n 开关传递一个字符串。

关于ruby - 如何使用 Ruby OptionParser 指定所需的开关(不是参数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1541294/

相关文章:

c - 指向指针参数数组的指针与本地

javascript - Ruby 哈希到 JavaScript

ruby-on-rails - 如何测试 Rspec 中不存在的 url?

ruby - 为 Windows 创建 Ruby 应用程序

php - 如何将参数传递给 codeigniter 方法

python - 从/使用函数参数作为键和默认值作为值创建字典

ruby-on-rails - 工厂女孩有一个协会

ruby - 无法使用 OptionParser 和 rspec

boolean 选项的 Ruby OptionParser 短代码?

ruby - OptionParser 中的 Nil 参数