How to count identical string elements in a Ruby array

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

    names = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"]
    Hash[names.group_by{|i| i }.map{|k,v| [k,v.size]}]
    # => {"Jason"=>2, "Teresa"=>1, "Judah"=>3, "Michelle"=>1, "Allison"=>1}
    

提交回复
热议问题