我正在尝试使用 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/