How to count duplicates in Ruby Arrays

后端 未结 16 1770
清歌不尽
清歌不尽 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:48

    Another way to do it is to use each_with_object:

    a = [ 1, 2, 3, 3, 4, 3]
    
    hash = a.each_with_object({}) {|v, h|
      h[v] ||= 0
      h[v] += 1
    }
    
    # hash = { 3=>3, 2=>1, 1=>1, 4=>1 } 
    

    This way, calling a non-existing key such as hash[5] will return nil instead of 0 with Kim's solution.

提交回复
热议问题