Hugo Demiglio Hugo Demiglio - 6 months ago 12
Ruby Question

How is the best way to merge array of hashes based on same value of some key?

I have some array of hashes with same keys. Like this below:

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


I need to organize them based on value of some key, generating a new hash with keys based on values of some key of original hash, like
type
.

I do this for organize:

by_type = {}
entities.each do |entity|
by_type[entity[:type]] ||= []
by_type[entity[:type]] << entity
end


Resulting on what I need:

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


There is another way or an elegant method to organize this?

Answer

You could use group_by:

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