mardi 7 juin 2016

How 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]] = [] unless by_type.has_key?(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?

Aucun commentaire:

Enregistrer un commentaire