簡體   English   中英

Ruby:如何將整數和范圍的字符串(ARGV)表示轉換為整數數組

[英]Ruby: How do I convert a string (ARGV) representation of integers and ranges to an array of integers

在Ruby中,我如何獲取表示整數或范圍的標記數組,並將它們解析為包含每個整數和每個范圍中每個元素的整數數組?

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

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

謝謝。

[ "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

像下面這樣的東西應該工作。 只需將輸入傳遞給方法並獲取整數數組即可。 我保持故意冗長,所以你可以看到邏輯。

編輯 :我已經在代碼中添加了注釋。

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

在您的示例輸入上運行此代碼會生成您的示例輸出,因此我相信它的位置。

嗯,實際上這可能需要一些工作。 我現在就解決一下:

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
>> [ "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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM