Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

building an array from several ranges

Tags:

arrays

ruby

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?

like image 977
dax Avatar asked Dec 24 '22 19:12

dax


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]
like image 98
Ajedi32 Avatar answered Jan 13 '23 09:01

Ajedi32


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]
like image 39
B Seven Avatar answered Jan 13 '23 11:01

B Seven