Ruby:如何将整数和范围的字符串(ARGV)表示转换为整数数组

时间:2010-10-22 04:44:49

标签: ruby text-parsing

在Ruby中,我如何获取表示整数或范围的标记数组,并将它们解析为包含每个整数和每个范围中每个元素的整数数组?

示例:给定输入[ "5", "7-10", "24", "29-31"]

我想生成输出[ 5, 7, 8, 9, 10, 24, 29, 30, 31 ]

感谢。

4 个答案:

答案 0 :(得分:3)

[ "5", "7-10", "24", "29-31"].map{|x| x.split("-").map{|val| val.to_i}}.map{ |y| Range.new(y.first, y.last).to_a}.flatten

答案 1 :(得分:1)

以下内容应该有效。只需将输入传递给方法并获取整数数组即可。我保持故意冗长,所以你可以看到逻辑。

修改:我已在代码中添加了评论。

def generate_output(input)
    output = []
    input.each do |element|
        if element.include?("-")
            # If the number is a range, split it
            split = element.split("-")
            # Take our split and turn it into a Ruby Range object, then an array
            output << (split[0].to_i..split[1].to_i).to_a
        else
            # If it's not a range, just add it to our output array
            output << element.to_i
        end
    end
    # Since our ranges will add arrays within the output array, calling flatten
    # on it will make it one large array with all the values in it.
    return output.flatten
end

在您的示例输入上运行此代码会生成您的示例输出,因此我相信它已经出现了。

答案 2 :(得分:1)

嗯,实际上这可能需要一些工作。我现在就解决它:

def parse_argv_list(list)
   number_list = []
   list.each do |item|
      if item.include?('-')
         bounds = item.split('-')
         number_list.push((bounds[0].to_i..bounds[1].to_i).to_a)
      else
         number_list.push(item.to_i)
      end
   end
   number_list.flatten
end

答案 3 :(得分:0)

>> [ "5", "7-10", "24", "29-31"].map{|x|x.gsub!(/-/,"..");x[".."]?(eval x).to_a : x.to_i}.flatten
=> [5, 7, 8, 9, 10, 24, 29, 30, 31]