Building an array from multiple ranges

I want to build an array of several ranges. The following works:

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] 

and this is certainly much better than typing a bunch of numbers - but I suspect there is a cleaner and cleaner way to do this. Any ideas?

+4
source share
2 answers

You can use the splat operator to do this quite cleanly:

[*70..89, *184..193, *224..233, *296..304, *336..345]

Result:

[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]
+9
source
def arrays_from *ranges
  ranges.map do |r|
    r.to_a
  end.flatten
end

or

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]
+1
source

Source: https://habr.com/ru/post/1589488/


All Articles