Ruby:OptionParser:String Arg &哈希分配
使用 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)
Using OptionParser for string argument input and hash assignment. What is the best way to read-in multiple variables for a single argument? How do I then assign those to a hash to reference? Here is what I have so far:
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
给定输入:
此代码
产生此输出:
请注意,我没有为每个选项使用 String 类型,而是使用 Array。这让 OptionParser 能够完成将元素解析为数组的繁重工作。从那时起,您就可以决定如何处理数组元素了。
Given an input of:
This code
Produces this output:
Notice that instead of using types of String for each option, I'm using Array. That lets OptionParser do the heavy lifting of parsing the elements into an array. From that point it's up to you what you do with the array elements.
我认为你处理这个问题的方式是错误的。您希望用户必须跟踪他们输入的参数的顺序,但您不想自己在代码中执行此操作!
你不要要求任何人跟踪什么与什么相关并使其明确如何:
代码:
结果:
I think you are approaching this the wrong way. You want your users to have to keep track of the order of the parameters they input but you don't want to do it yourself in the code!
How about you don't ask anybody to keep track of what goes with what and make it explicit:
Code:
result: