Skip to content

Instantly share code, notes, and snippets.

@sj26
Created January 4, 2012 06:03
Show Gist options
  • Save sj26/1558727 to your computer and use it in GitHub Desktop.
Save sj26/1558727 to your computer and use it in GitHub Desktop.
Sorting and merging a set of numbers and ranges
postcodes = [2000, 3000..3004, 3005, 3010..3020, 3015..3025, 4000..4020, 4010]
postcodes.map do |number_or_range|
if number_or_range.is_a? Numeric
(number_or_range..number_or_range)
elsif number_or_range.is_a? Range
number_or_range if number_or_range.count > 0
end
end.compact.sort_by(&:begin).inject([]) do |ranges, range|
ranges.tap do
if ranges.last and (ranges.last.include? range.begin or ranges.last.include? range.begin - 1)
unless ranges.last.include? range.end
ranges[-1] = (ranges.last.begin..range.end)
end
else
ranges << range
end
end
end
# => [2000..2000, 3000..3005, 3010..3025, 4000..4020]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment