How to count identical string elements in a Ruby array

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

    a = [1, 2, 3, 2, 5, 6, 7, 5, 5]
    a.each_with_object(Hash.new(0)) { |o, h| h[o] += 1 }
    
    # => {1=>1, 2=>2, 3=>1, 5=>3, 6=>1, 7=>1}
    

    Credit Frank Wambutt

提交回复
热议问题