gpt4 book ai didi

ruby - Ruby 中的命令行选项解析

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:43 25 4
gpt4 key购买 nike

我有一个 ruby​​ 脚本,可以按如下方式解析提供给它的命令行选项:

#!/usr/bin/ruby

require 'optparse'

puts 'Hello World!, This is my first ruby program'

options = {}

optparse = OptionParser.new do|opts|

opts.banner = "Featbuild minimal trial script for command line parsing"

options[:cpl] = nil
opts.on('-cpl SWITCH_STATE', 'compile on or off') do|cplopt|
options[:cpl] = cplopt
OPT_CPL=cplopt
puts cplopt
end

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

optparse.parse!

output = open("mypipe", "w+")

output.puts OPT_CPL
#output.flush

现在,上面脚本中的 opts.on('-cpl SWITCH_STATE', 'compile on or off') do|cplopt| 行是我遇到问题的地方。

我相信我们可以通过以下方式做到这一点:1.)opts.on('--cpl SWITCH_STATE', '编译开启或关闭') do|cplopt|2.)opts.on('-c', '--cpl SWITCH_STATE', '编译开启或关闭') do|cplopt|3.)opts.on('-cpl SWITCH_STATE', '编译开启或关闭') do|cplopt|

这是我传递的有效参数:

$./try1.rb --cpl on
$./try1.rb -c on

这不起作用: $./try1.rb -cpl on

Ruby 不是将“on”作为选项参数,而是“pl”,就好像指定了 $./try.rb -c pl 一样。

我想让字符串 $./try1.rb -cpl on'on' 传递给方法 block 的方式进行解析opts.on()'cplopt' 中。

我指的是本教程:http://ruby.about.com/od/advancedruby/a/optionparser2.htm

似乎 '-cpl on' 在 Ruby 中是不可能的?是这样吗?

我还可以在这里应用哪些其他替代解决方案?

最佳答案

尝试 Trollop ,因为它使选项解析生活更容易。

require 'trollop'
opts = Trollop::options do
version "compile 0.1.0"
banner "Usage: compile <option> - where [options] are:"
opt :cpl, "compile on or off", :type => :string, :default => "off"
end
puts opts.cpl

运行时,结果:

$ ruby ./trollop.rb --cpl on
on

$ ruby ./trollop.rb --cpl off
off

$ ruby ./trollop.rb -c on
on

$ ruby ./trollop.rb -c off
off

$ ruby ./trollop.rb
off


Trollop 2.0 支持 no- negation of boolean options您可能会发现这比处理 on/off 字符串更容易。

opt "cpl", "Compile", :default => true

运行时,结果:

$ ruby trollop.rb --cpl
true

$ ruby trollop.rb --no-cpl
false

关于ruby - Ruby 中的命令行选项解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24757538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com