Ruby on rails 基于某个键的相同值合并哈希数组的最佳方法是什么?

Ruby on rails 基于某个键的相同值合并哈希数组的最佳方法是什么?,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,hash,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

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

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

有另一种方法或优雅的方法来组织这项工作吗?

您可以使用
group\u by

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