简体   繁体   English

如何基于某个键的相同值合并哈希数组的最佳方法?

[英]How is the best way to merge array of hashes based on same value of some key?

I have some array of hashes with same keys. 我有一些具有相同键的散列。 Like this below: 如下所示:

entities = [
  {type: :user, name: 'Tester', phone: '0000-0000'},
  {type: :user, name: 'Another User', phone: '0000-0000'},
  {type: :company, name: 'A.C.M.E.', phone: '0000-0000'},
  {type: :user, name: 'John Appleseed', phone: '0000-0000'},
  {type: :company, name: 'Aperture Industries', phone: '0000-0000'}
]

I need to organize them based on value of some key, generating a new hash with keys based on values of some key of original hash, like type . 我需要根据某个键的值来组织它们,并根据原始哈希(如type中某个键的值生成一个带有键的新哈希。

I do this for organize: 我这样做是为了整理:

by_type = {}
entities.each do |entity|
  by_type[entity[:type]] ||= []
  by_type[entity[:type]] << entity
end

Resulting on what I need: 结果我需要:

by_type = {
  user: [
    {type: :user, name: 'Tester', phone: '0000-0000'},
    {type: :user, name: 'Another User', phone: '0000-0000'},
    {type: :user, name: 'John Appleseed', phone: '0000-0000'}
  ],
  company: [
    {type: :company, name: 'A.C.M.E.', phone: '0000-0000'},
    {type: :company, name: 'Aperture Industries', phone: '0000-0000'}
  ]
}

There is another way or an elegant method to organize this? 还有另一种方法或一种优雅的方法来组织此活动吗?

您可以使用group_by

entities.group_by { |entity| entity[:type] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM