Ruby:如何对 Ruby 数组进行分组? [英] Ruby: How to group a Ruby array?

查看:106
本文介绍了Ruby:如何对 Ruby 数组进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Ruby 数组

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}

所以理想情况下,我想要一个哈希值,它可以为我提供计数并注意我如何拥有 Enter Sandmanenter sandman 所以我需要它不区分大小写.我很确定我可以循环遍历它,但有更简洁的方法吗?

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?

推荐答案

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

group by 创建从专辑名称的 capitalized 版本到包含 list 中匹配它的所有字符串的数组的哈希值(例如 "输入 Sandman" => ["输入 Sandman", "输入 Sandman"]).map 然后用它的长度替换每个数组,所以你得到例如["进入sandman", 2] for "进入sandman".

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

如果你需要结果是一个哈希值,你可以对结果调用 to_h 或者在它周围包裹一个 Hash[ ] .

If you need the result to be a hash, you can call to_h on the result or wrap a Hash[ ] around it.

这篇关于Ruby:如何对 Ruby 数组进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆