按键分组哈希数组 [英] Group array of hashes by key

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

问题描述

我有一个由以下形式的哈希组成的数组:

I have an array consisting of hashes in the following form:

[
  {:user=>"mike" etc},
  {:user=>"mike" etc},
  {:user=>"peter" etc},
  {:user=>"joe" etc}
]

是否有任何方便的方法可以根据用户密钥的值来拆分组?最终结果应该是这样的:

Are there any convenient ways to split the group according to the value of user key? The final result should be something like this:

[
  [{:user=>"mike" etc}, {:user=>"mike" etc}],
  [{:user=>"peter" etc}],
  [{:user=>"joe" etc}]
]

推荐答案

使用group_by.

array.group_by{|h| h[:user]}.values

这篇关于按键分组哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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