【发布时间】:2016-10-07 15:31:27
【问题描述】:
我有一些具有相同键的哈希数组。如下所示:
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'}
]
}
还有其他方式或优雅的方法来组织这个吗?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 hash