Ruby - collect same numbers from array into array of arrays

前端 未结 4 1952
难免孤独
难免孤独 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]]
    
    0 讨论(0)
  • 2021-01-28 06:46

    In case if you want to do it without order:

    ar.group_by(&:itself).values
     => [[5, 5], [2, 2, 2], [6, 6]]
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-28 07:01

    just another oneliner

    arr = [5, 5, 2, 2, 2, 6, 6] 
    arr.uniq.map {|e| [e]*arr.count(e) }
    # => [[5, 5], [2, 2, 2], [6, 6]] 
    
    0 讨论(0)
提交回复
热议问题