gpt4 book ai didi

ruby - 将数组中的连续数字分组

转载 作者:数据小太阳 更新时间:2023-10-29 07:20:50 28 4
gpt4 key购买 nike

我需要将连续的数字添加到一个新数组中,如果不是连续的数字,则只将该值添加到一个新数组中:

old_array = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]

我想得到这个结果:

 new_array = [
[1,2,3],
[5],
[7,8,9]
[20,21]
[23],
[29]
]

有更简单的方法吗?

最佳答案

这次聚会有点晚了但是:

old_array.slice_when { |prev, curr| curr != prev.next }.to_a
# => [[1, 2, 3], [5], [7, 8, 9], [20, 21], [23], [29]]

关于ruby - 将数组中的连续数字分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23840815/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com