Grouping an array by comparing 2 adjacent elements

后端 未结 3 1502
难免孤独
难免孤独 2021-01-21 05:10

I have an array of objects and I would like to group them based on the difference between the attributes of 2 adjacent elements. The array is already sorted by that attribute. F

3条回答
  •  佛祖请我去吃肉
    2021-01-21 05:45

    array = [1, 3, 6, 9, 10]
    prev = array[0]
    p array.slice_before{|el| prev,el = el,prev; prev-el > 2}.to_a
    
    # => [[1, 3], [6], [9, 10]]
    

提交回复
热议问题