ruby - Complete and order a list of ranges? -
ruby - Complete and order a list of ranges? -
i have next ranges:
(800..1200) (800..1600) (800..1700) (800..1900) (900..1500) (1000..2000) (2200..2300) and want array this:
[(800..900), (900..1000), (1000..1200), (1200..1500), (1500..1600), (1600..1700), (1700..1900), (1900..2000), (2000..2200), (2200..2300)] the expected array (ranges) ordered list of ranges, ranges[n+1].min == ranges[n].max. shouldn't have gap between ranges.
i have succeeded write code this, it's long list of if/else in loop, , not readable. wondering if has thought on how more concisely?
this should it.
a = [(800..1200), (800..1600), (800..1700), (800..1900), (900..1500), (1000..2000), (2200..2300)] a.each_with_object([]) { |r,a| << r.first << r.last } .uniq .sort .each_cons(2) .to_a .map { |a,b| a..b } #=> [800..900, 900..1000, 1000..1200, 1200..1500, 1500..1600, # 1600..1700, 1700..1900, 1900..2000, 2000..2200, 2200..2300] ruby
Comments
Post a Comment