Ruby:OptionParser:String Arg&哈希分配

时间:2010-10-02 17:00:42

标签: ruby variables split variable-assignment optionparser

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

2 个答案:

答案 0 :(得分: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可以将元素解析成数组。从那时起,您可以使用数组元素来处理它。

答案 1 :(得分: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' ] ]