Ruby: How to group a Ruby array?

后端 未结 6 1315
执念已碎
执念已碎 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:33

    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 capitalized 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.

提交回复
热议问题