How to count identical string elements in a Ruby array

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

    Lots of great implementations here.

    But as a beginner I would consider this the easiest to read and implement

    names = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"]
    
    name_frequency_hash = {}
    
    names.each do |name|
      count = names.count(name)
      name_frequency_hash[name] = count  
    end
    #=> {"Jason"=>2, "Teresa"=>1, "Judah"=>3, "Michelle"=>1, "Allison"=>1}
    

    The steps we took:

    • we created the hash
    • we looped over the names array
    • we counted how many times each name appeared in the names array
    • we created a key using the name and a value using the count

    It may be slightly more verbose (and performance wise you will be doing some unnecessary work with overriding keys), but in my opinion easier to read and understand for what you want to achieve

提交回复
热议问题