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

时间:2016-06-07 16:09:09

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 hash

我有一些具有相同键的哈希数组。如下所示:

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

还有另一种方法或优雅方法来组织这个吗?

1 个答案:

答案 0 :(得分:2)

您可以使用group_by

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