我想用几个范围构建一个数组。以下作品:
array_of_ranges = (70..89).to_a + (184..193).to_a + (224..233).to_a + (296..304).to_a + (336..345).to_a
=> [70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 296, 297, 298, 299, 300, 301, 302, 303, 304, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345]
它肯定比输入一堆数字要好得多 - 但我怀疑它有更好,更清洁的方法。有任何想法吗?
答案 0 :(得分:9)
您可以使用splat运算符来非常干净地执行此操作:
[*70..89, *184..193, *224..233, *296..304, *336..345]
结果:
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 296, 297, 298, 299, 300, 301, 302, 303, 304, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345]
答案 1 :(得分:1)
def arrays_from *ranges
ranges.map do |r|
r.to_a
end.flatten
end
或
def arrays_from *ranges
ranges.map( &:to_a ).flatten
end
arrays_from 70..89, 184..193, 224..233
=> [70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233]