我有一些具有相同键的哈希数组。如下所示:
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'}
]
}
还有另一种方法或优雅方法来组织这个吗?
答案 0 :(得分:2)
您可以使用group_by
:
entities.group_by { |entity| entity[:type] }