Ruby: How to group a Ruby array? -


i have 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 want list counts this:

{"nothing else matters" => 1,  "enter sandman" => 2,  "master of puppets" => 3} 

so ideally want hash give me count , notice how have enter sandman , enter sandman need case insensitive. pretty sure can loop through there cleaner way?

list.group_by(&:capitalize).map {|k,v| [k, v.length]} #=> [["master of puppets", 3], ["enter sandman", 2], ["nothing else matters", 1]] 

the group creates hash capitalized version of album name array containing strings in list match (e.g. "enter sandman" => ["enter sandman", "enter sandman"]). map replaces each array length, e.g. ["enter sandman", 2] "enter sandman".

if need result hash, can call to_h on result or wrap hash[ ] around it.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -