4

使用 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)
4

2 回答 2

7

给定输入:

 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 可以完成将元素解析为数组的繁重工作。从那时起,由您决定如何处理数组元素。

于 2010-10-03T19:45:49.997 回答
5

我认为您以错误的方式处理此问题。您希望您的用户必须跟踪他们输入的参数的顺序,但您不想在代码中自己做!

您不要求任何人跟踪与什么相关的内容并明确说明如何:

ruby test.rb --input bName1,lSku1,wQueue1 --input bName2,lSku2,wQueue2 --input bNameN,lSkuN,wQueueN

代码:

opts.on("--input <brand,Large_Skus,Small_Skus>", "input description",
        "NOTE: Can be used more than once.") do |opt|
  list = opt.split(',')
  unless list.lenght == 3
    raise "some error because you didn't place all arguments"
  end
  options[:input].push list
end 

结果:

[ [ 'bName1', 'lSku1', 'wQueue1' ],
  [ 'bName2', 'lSku2', 'wQueue2' ],
  [ 'bNameN', 'lSkuN', 'wQueueN' ] ]
于 2013-03-26T14:16:25.130 回答