在Ruby中,如何获取表示整数或范围的标记数组,并将它们解析为包含每个整数和每个范围中的每个元素的整数数组?
示例:给定输入[ "5", "7-10", "24", "29-31"]
我想要产生输出[ 5, 7, 8, 9, 10, 24, 29, 30, 31 ]
谢谢。
发布于 2010-10-22 13:01:33
[ "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发布于 2010-10-22 12:52:19
下面这样的代码应该可以工作。只需将您的输入传递给该方法并获得一个整数数组即可。我故意让它变得冗长,这样你就可以看到其中的逻辑。
编辑:我已经在代码中添加了注释。
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在您的示例输入上运行此代码将生成示例输出,因此我相信它是正确的。
发布于 2010-10-22 12:55:30
嗯,实际上,这可能需要一些工作。我现在就来试一试:
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
endhttps://stackoverflow.com/questions/3993956
复制相似问题