How to count duplicates in Ruby Arrays

后端 未结 16 1759
清歌不尽
清歌不尽 2020-12-01 06:21

How do you count duplicates in a ruby array?

For example, if my array had three a\'s, how could I count that

16条回答
  •  既然无缘
    2020-12-01 06:52

    Given:

    arr = [ 1, 2, 3, 2, 4, 5, 3]
    

    My favourite way of counting elements is:

    counts = arr.group_by{|i| i}.map{|k,v| [k, v.count] }
    
    # => [[1, 1], [2, 2], [3, 2], [4, 1], [5, 1]]
    

    If you need a hash instead of an array:

    Hash[*counts.flatten]
    
    # => {1=>1, 2=>2, 3=>2, 4=>1, 5=>1}
    

提交回复
热议问题