Ruby: How to group a Ruby array?
list.group_by(&:capitalize).map {|k,v| [k, v.length]}
#=> [["Master of puppets", 3], ["Enter sandman", 2], ["Nothing else matters", 1]]
The group by creates a hash from the capitalize
d version of an album name to an array containing all the strings in list
that match it (e.g. "Enter sandman" => ["Enter Sandman", "Enter sandman"]
). The map
then replaces each array with its length, so you get e.g. ["Enter sandman", 2]
for "Enter sandman"
.
If you need the result to be a hash, you can call to_h
on the result or wrap a Hash[ ]
around it.
list.inject(Hash.new(0)){|h,k| k.downcase!; h[k.capitalize] += 1;h}
Another take:
h = Hash.new {|hash, key| hash[key] = 0}
list.each {|song| h[song.downcase] += 1}
p h # => {"nothing else matters"=>1, "enter sandman"=>2, "master of puppets"=>3}
As I commented, you might prefer titlecase