Ruby: How to group a Ruby array?

Viewed 65171

I have a Ruby array

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

and I want a list with the counts like this:

{"Nothing Else Matters" => 1,
 "Enter Sandman" => 2,
 "Master of Puppets" => 3}

So ideally I want a hash that will give me the count and notice how I have Enter Sandman and enter sandman so I need it case insensitive. I am pretty sure I can loop through it but is there a cleaner way?

6 Answers

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}

Late but clean answer I have,

l = list.group_by(&:titleize)
l.merge(l) { |k,v| l[k] = v.count }

Note: If we do want unique keys i.e. without titleize, then replace it with itself

Related