How to count identical string elements in a Ruby array

前端 未结 14 2140
感情败类
感情败类 2020-12-02 06:34

I have the following Array = [\"Jason\", \"Jason\", \"Teresa\", \"Judah\", \"Michelle\", \"Judah\", \"Judah\", \"Allison\"]

How do I produce a count for

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 07:10

    names.inject(Hash.new(0)) { |total, e| total[e] += 1 ;total}
    

    gives you

    {"Jason"=>2, "Teresa"=>1, "Judah"=>3, "Michelle"=>1, "Allison"=>1} 
    

提交回复
热议问题