ruby - 在 Ruby 中,OptionParser 返回 bool 值而不是输入值

标签 ruby arguments optparse

我正在尝试使用 OptionParser 获取参数值。 我的代码只返回 bool 值,而不是值:

require 'optparse'

options ={}
opts = OptionParser.new do |opts|
opts.on('-v')    { |version| options[:version] = version }
opts.on('-g')    { |branch| options[:branch] = branch }
opts.on('-f')    { |full| options[:full] = full }
opts.on('-h')    { RDoc::usage }
end.parse!

# mandatory options
if (options[:version] == nil)  or (options[:branch] == nil) or (options[:full]== nil) then
    puts options[:branch]
    puts options[:version]
    puts options[:full]
    RDoc::usage('usage')
end

puts options[:branch]

---> 正确

有什么想法吗?

最佳答案

如果你想获取一个值,你需要请求它:

opts = OptionParser.new do |opts|
opts.on('-v=s') { |version| options[:version] = version }
opts.on('-g=s') { |branch| options[:branch] = branch }
opts.on('-f=s') { |full| options[:full] = full }
opts.on('-h') { RDoc::usage }

=s 表示法表示存在关联值。

在定义这样的接口(interface)时,为了清晰起见,不要忘记包含长格式名称,例如 --version--branch,这样人们就不必记住g 表示“分支”。

所有这些都包含在 fantastic documentation 中我鼓励您阅读。

关于ruby - 在 Ruby 中,OptionParser 返回 bool 值而不是输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36910010/

相关文章:

python - 你如何处理不能一起使用的选项(使用 OptionParser)?

ruby - 是否有默认变量 `hash` ?

ruby-on-rails - Rails 4 嵌套资源哈希未提交到数据库

c - 函数指针和函数由于参数不兼容

python - 如何在 Python argparse 中使用 `--foo 1 --foo 2` 样式参数?

r - 在 R 中通过命令行传递多个参数

ruby-on-rails - Ruby on Rails : Operation now in progress - connect(2) would block

ruby-on-rails - 通过将 Rails 保留在内存中来加快开发过程中的 Rails 测试?

c - 是 printf(c);是有效的语法(其中 c 是字符串文字)?

python - 从 optparse 传递可选参数