How to count duplicates in Ruby Arrays

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

    Its Easy:

    words = ["aa","bb","cc","bb","bb","cc"]
    

    One line simple solution is:

    words.each_with_object(Hash.new(0)) { |word,counts| counts[word] += 1 }
    

    It works for me.

    Thanks!!

提交回复
热议问题