我正在浏览ruby中的OptionsParser tutorial。有一行我很困惑的代码:
option_parser = OptionParser.new do |opt|
.
.
.
server_list = %w[a b c]
opt.on("-s SERVERS","--servers SERVERS", server_list, "which server will start between #{server_list.join(',')}") do |servers|
options[:servers] = servers
end
我理解OptionParser#on
可以将值转换为例如:
.
.
.
opt.on("-e","--environment ENVIRONMENT",Numeric, "which environment you want server run") do |environment|
puts environment #=> Fixnum
options[:environment] = environment
end
但是我还没弄清楚如何成功运行使用OptionParser的ruby程序,如上所示。请参阅下文,了解我的尝试。
➜ ruby-cli cat 04-with_optparse_convert_values
#!/usr/bin/env ruby
require 'optparse'
options = {}
option_parser = OptionParser.new do |opt|
opt.banner = "Usage: cats"
opt.on("-e", "--environment ENVIRONMENT", Numeric, "environment to run") do |env|
puts "env.class"
p env.class
options[:environment] = env
end
opt.on("--delay N", Float, "Delay N seconds before executing") do |n|
options[:delay] = n
end
opt.on("-j x,y,z","--jurisdictions x,y,z", Array,
"which jurisdiction will start") do |jurisdictions|
options[:jurisdictions] = jurisdictions
end
server_list = %w[a b c]
opt.on("-s SERVERS","--servers SERVERS", server_list,
"which server will start between #{server_list.join(',')}") do |servers|
options[:servers] = servers
end
end
option_parser.parse!
p options
➜ ruby-cli ./04-with_optparse_convert_values -j cats,and,dogs
{:jurisdictions=>["cats", "and", "dogs"]}
➜ ruby-cli ./04-with_optparse_convert_values -j cats,and,dogs -s cats,and,dogs
./04-with_optparse_convert_values:33:in `<main>': invalid argument: -s cats,and,dogs (OptionParser::InvalidArgument)
➜ ruby-cli ./04-with_optparse_convert_values -j cats,and,dogs -s cats
./04-with_optparse_convert_values:33:in `<main>': invalid argument: -s cats (OptionParser::InvalidArgument)
➜ ruby-cli ./04-with_optparse_convert_values -j cats,and,dogs -s "cats,and,dogs"
./04-with_optparse_convert_values:33:in `<main>': invalid argument: -s cats,and,dogs (OptionParser::InvalidArgument)
➜ ruby-cli ./04-with_optparse_convert_values -j cats,and,dogs -s "cats\nand\ndogs"
./04-with_optparse_convert_values:33:in `<main>': invalid argument: -s cats\nand\ndogs (OptionParser::InvalidArgument)
➜ ruby-cli ARRAY=(cats and dogs)
➜ ruby-cli ./04-with_optparse_convert_values -j cats,and,dogs -s ${ARRAY[\*]}
./04-with_optparse_convert_values:33:in `<main>': invalid argument: -s cats (OptionParser::InvalidArgument)
➜ ruby-cli
答案 0 :(得分:0)
server_list = %w[a b c]
opt.on("-s SERVERS","--servers SERVERS", server_list,
"which server will start between #{server_list.join(',')}") do |servers|
options[:servers] = servers
end
提供一系列&#34;服务器&#34;通过命令行选项-s
进行选择,因此,./04-with_optparse_convert_values -s cats
不起作用,因为它不是其中一个选项,而是a
,b
或{ {1}}会。例如:
c