我有以下范围:
(800..1200)
(800..1600)
(800..1700)
(800..1900)
(900..1500)
(1000..2000)
(2200..2300)
想得到这样的数组:
[(800..900), (900..1000), (1000..1200), (1200..1500), (1500..1600), (1600..1700), (1700..1900), (1900..2000), (2000..2200), (2200..2300)]
预期的数组(范围)是范围的有序列表,其中范围[n + 1] .min == range [n] .max。我们不应该在范围之间有任何差距。
我已经成功编写了执行此操作的代码,但它是循环中if / else的长列表,并且不太可读。我想知道是否有人知道如何更简洁地做到这一点?
答案 0 :(得分:1)
这应该这样做。
a = [(800..1200), (800..1600), (800..1700), (800..1900),
(900..1500), (1000..2000), (2200..2300)]
a.each_with_object([]) { |r,a| 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]