基于某个键的相同值合并哈希数组的最佳方法是什么?
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] }
我有一些具有相同键的散列数组。像下面这样:
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] }