How to count duplicates in Ruby Arrays

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

    Another version of a hash with a key for each element in your array and value for the count of each element

    a = [ 1, 2, 3, 3, 4, 3]
    h = Hash.new(0)
    a.each { | v | h.store(v, h[v]+1) }
    
    # h = { 3=>3, 2=>1, 1=>1, 4=>1 } 
    

提交回复
热议问题