Ruby - collect same numbers from array into array of arrays

前端 未结 4 1992
难免孤独
难免孤独 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:52

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

    One could perhaps say that Enumerable#chunk_while and Enumerable#slice_when are ying and yang.

    Prior to Ruby v2.3, one might write

    [5, 5, 2, 2, 2, 6, 6].chunk(&:itself).map(&:last)
    

    and prior to v2.2,

    [5, 5, 2, 2, 2, 6, 6].chunk { |n| n }.map(&:last)
    

提交回复
热议问题