使用 OptionParser 进行字符串参数输入和哈希赋值。为单个参数读入多个变量的最佳方法是什么?然后我如何将它们分配给散列以供引用?这是我到目前为止所拥有的:
large_skus = Hash.new
small_skus = Hash.new
OptionParser.new do |opts|
opts.on("-b", "--brands bName1,bName2,bNameN", String, "Check specific brands by name") do |b|
options[:brands] = b.split(",")
end
opts.on("-l", "--large lSku1,lSku2,lSkuN", String, "Large SKUs - List CSVs") do |l|
options[:large_skus] = l.split(",")
##For each sku given
brandName = options[:brands]
large_skus[brandName] = l[$sku].to_i
##
end
opts.on("-s", "--small sSku1,sSku2,sSkuN", String, "Small SKUs - List CSVs") do |s|
options[:small_skus] = s.split(",")
##For each sku given
brandName = options[:brands]
small_skus[brandName] = s[$sku].to_i
##
end
end.parse!(ARGV)
最佳答案
给定输入:
ruby test.rb --brands bName1,bName2,bNameN --large lSku1,lSku2,lSkuN --small wQueue1,wQueue2,wQueueN
这段代码
#!/usr/bin/env ruby
require 'ap'
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.on("-b", "--brands bName1,bName2,bNameN", Array, "Check specific brands by name") do |b|
options[:brands] = b
end
opts.on("-l", "--large lSku1,lSku2,lSkuN", Array, "Large SKUs - List CSVs") do |l|
options[:large_skus] = l
end
opts.on("-s", "--small wQueue1,wQueue2,wQueueN", Array, "Small SKUs - List CSVs") do |s|
options[:small_skus] = s
end
end.parse!(ARGV)
ap options
产生这个输出:
{
:brands => [
[0] "bName1",
[1] "bName2",
[2] "bNameN"
],
:large_skus => [
[0] "lSku1",
[1] "lSku2",
[2] "lSkuN"
],
:small_skus => [
[0] "wQueue1",
[1] "wQueue2",
[2] "wQueueN"
]
}
请注意,我没有为每个选项使用 String 类型,而是使用 Array。这让 OptionParser 完成将元素解析为数组的繁重工作。从那时起,您如何处理数组元素取决于您。
关于Ruby:OptionParser:字符串参数和哈希赋值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3846683/