Skip to content

Instantly share code, notes, and snippets.

@damonjmurray
Last active August 29, 2015 14:20
Show Gist options
  • Save damonjmurray/a5d551d4733222ef3b0e to your computer and use it in GitHub Desktop.
Save damonjmurray/a5d551d4733222ef3b0e to your computer and use it in GitHub Desktop.
Slightly read-friendlier version of integers_to_ranges method... perhaps?
# receive an array of ints, compact it, order the elements, and group them into ranges
# original:
def get_ranges_in(values_array)
return [] if values_array.nil?
values_array.compact.sort.uniq.inject([]) do |r,x|
r.empty? || r.last.last.succ != x ? r << (x..x) : r[0..-2] << (r.last.first..x)
end
end
# expanded:
def get_ranges_in(values_array)
return [] if values_array.nil?
next_upper_value_for = lambda { | range_array | range_array.last.last.succ }
current_lower_value_for = lambda { | range_array | range_array.last.first }
source = values.compact.sort.uniq
source.inject([]) do |r, x|
if r.empty? || x != next_upper_value_for[r]
r << (x..x)
else
# replace last element with corrected upper value
r[0..-2] << (current_lower_value_for[r]..x)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment