How to count identical string elements in a Ruby array

前端 未结 14 2204
感情败类
感情败类 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:16

    Now using Ruby 2.2.0 you can leverage the itself method.

    names = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"]
    counts = {}
    names.group_by(&:itself).each { |k,v| counts[k] = v.length }
    # counts > {"Jason"=>2, "Teresa"=>1, "Judah"=>3, "Michelle"=>1, "Allison"=>1}
    

提交回复
热议问题