繁体   English   中英

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

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

我有一些具有相同键的散列。 如下所示:

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'}
]

我需要根据某个键的值来组织它们,并根据原始哈希(如type中某个键的值生成一个带有键的新哈希。

我这样做是为了整理:

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

结果我需要:

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'}
  ]
}

还有另一种方法或一种优雅的方法来组织此活动吗?

您可以使用group_by

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

暂无
暂无

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

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