Ruby - collect same numbers from array into array of arrays

前端 未结 4 1951
难免孤独
难免孤独 2021-01-28 06:02

I have created a very ugly script to collect same numbers from an array. I don\'t think this is a very Ruby way :) Anyone could provide a more clean solution?

ar         


        
4条回答
  •  隐瞒了意图╮
    2021-01-28 06:45

    Using chunk_while:

    [5, 5, 2, 2, 2, 6, 6].chunk_while(&:==).to_a
    #=> [[5, 5], [2, 2, 2], [6, 6]]
    

    Ruby prior to 2.3:

    [5, 5, 2, 2, 2, 6, 6].each_with_object([]) do |e, acc|
      acc.last && acc.last.last == e ? acc.last << e : acc << [e]
    end
    #=> [[5, 5], [2, 2, 2], [6, 6]]
    

提交回复
热议问题