Christian-G Christian-G - 5 months ago 10
Ruby Question

combine keys in array of hashes

I map results of my query to create an array of hashes grouped by

organisation_id
like so:

results.map do |i|
{
i['organisation_id'] => {
name: capability.name,
tags: capability.tag_list,
organisation_id: i['organisation_id'],
scores: {i['location_id'] => i['score']}
}
}


a
capability
is defined outside the map.

The result looks like:

[{1=>{:name=>"cap1", :tags=>["tag A"], :scores=>{26=>4}}}, {1=>{:name=>"cap1", :tags=>["tag A"], :scores=>{12=>5}}}, {2 => {...}}...]


For every
organisation_id
there is a separate entry in the array. I would like to merge these hashes and combine the
scores
key as so:

[{1=>{:name=>"cap1", :tags=>["tag A"], :scores=>{26=>4, 12=>5}}}, {2=>{...}}... ]


Any pointers?

Answer

I'll assume for each organization: the name, taglist and organization_id remains the same.

your_hash = results.reduce({}) do |h, i|
  org_id = i['organisation_id']
  h[org_id] ||= {
    name: capability.name, 
    tags: capability.taglist, 
    organisation_id: org_id,
    scores: {}
  }
  h[org_id][:scores][i['location_id']] = i['score']
  # If the location scores are not strictly exclusive, you can also just +=
  h
end
Comments