I want to build an array out 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 it's certainly much nicer than typing in a bunch of numbers - but I suspect there's a nicer, cleaner way to do this. Any ideas?
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With