在哈希数组中组合键

时间:2016-06-30 05:53:31

标签: ruby-on-rails ruby

我映射查询结果以创建按organisation_id分组的哈希数组,如下所示:

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

在地图外定义capability

结果如下:

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

对于每个organisation_id,数组中都有一个单独的条目。我想合并这些哈希值并将scores键合并为:

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

修改

要创建results我使用以下AR:

Valuation.joins(:membership)
         .where(capability: capability)
         .select("valuations.id, valuations.score, valuations.capability_id, valuations.membership_id, memberships.location_id, memberships.organisation_id")
         .map(&:serializable_hash)

Valuation型号:

class Valuation < ApplicationRecord
  belongs_to :membership
  belongs_to :capability
end

Membership型号:

class Membership < ApplicationRecord
  belongs_to :organisation
  belongs_to :location
  has_many :valuations
end

results摘录:

[{"id"=>1, "score"=>4, "capability_id"=>1, "membership_id"=>1, "location_id"=>26, "organisation_id"=>1}, {"id"=>16, "score"=>3, "capability_id"=>1, "membership_id"=>2, "location_id"=>36, "organisation_id"=>1}, {"id"=>31, "score"=>3, "capability_id"=>1, "membership_id"=>3, "location_id"=>26, "organisation_id"=>2}, {"id"=>46, "score"=>6, "capability_id"=>1, "membership_id"=>4, "location_id"=>16, "organisation_id"=>2}...

3 个答案:

答案 0 :(得分:1)

我假设每个组织:名称,标签列表和organization_id保持不变。

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

答案 1 :(得分:1)

我相信这有效,但需要数据来测试它。

results.each_with_object({}) do |i,h|
  h.update(i['organisation_id'] => {
    name: capability.name,
    tags: capability.tag_list,
    organisation_id: i['organisation_id'],
    scores: {i['location_id'] => i['score']}) { |_,o,n|
      o[:scores].update(n[:score]); o }
  }
end.values

这使用Hash#update(aka merge!)的形式,它使用块来确定合并的两个哈希中存在的键的值。有关每个块变量_on的内容,请参阅doc。

答案 2 :(得分:0)

假设result是你最后的哈希数组:

result.each_with_object({}) do |e, obj|
  k, v = e.flatten
  if obj[k]
    obj[k][:scores] = obj[k][:scores].merge(v[:scores])
  else
    obj[k] = v
  end
end