首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Ruby:如何将整数和范围的字符串(ARGV)表示形式转换为整数数组

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

Stack Overflow用户
提问于 2010-10-22 12:44:49
回答 4查看 2K关注 0票数 3

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

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

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

谢谢。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-10-22 13:01:33

代码语言:javascript
运行
复制
[ "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
票数 3
EN

Stack Overflow用户

发布于 2010-10-22 12:52:19

下面这样的代码应该可以工作。只需将您的输入传递给该方法并获得一个整数数组即可。我故意让它变得冗长,这样你就可以看到其中的逻辑。

编辑:我已经在代码中添加了注释。

代码语言:javascript
运行
复制
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

在您的示例输入上运行此代码将生成示例输出,因此我相信它是正确的。

票数 1
EN

Stack Overflow用户

发布于 2010-10-22 12:55:30

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

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3993956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档