您的位置:首页 > 编程语言 > Ruby

Slicing discontinuous data into continuous parts in Ruby

2015-05-24 09:38 399 查看
I have this discontinuous array:
a = [1, 2, 3, 7, 8, 10, 11, 12]


I need it to be an array of continuous arrays:

[[1,
2,
3],
[7,
8],
[10,
11,
12]]


method 1:


a = [1, 2, 3, 7, 8, 10, 11, 12]
prev = a[0] - 1
a.slice_before { |cur|  [prev + 1 != cur, prev = cur][0] }.to_a
# => [[1, 2, 3], [7, 8], [10, 11, 12]]

method 2:

a = [1, 2, 3, 7, 8, 10, 11, 12]
prev = a.first
p a.slice_before { |e|
prev, prev2 = e, prev
prev2 + 1 != e
}.to_a

method 3:

([a[0]] + a).each_cons(2).slice_before{|k, l| k + 1 != l}.map{|a| a.map(&:last)}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: