Ruby: How to group a Ruby array?

后端 未结 6 1302
执念已碎
执念已碎 2020-12-28 12:17

I have a Ruby array

> list = Request.find_all_by_artist(\"Metallica\").map(&:song)
=> [\"Nothing else Matters\", \"Enter sandman\", \"Enter Sandman         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 12:22

    As of Ruby 2.7, you can use Enumerable#tally.

    list.tally
    # => {"Nothing else Matters"=>1, "Enter sandman"=>1, "Enter Sandman"=>1, "Master of Puppets"=>3}
    

提交回复
热议问题