0

我有我的哈希的这种格式,我使用这个从我的数据库中获得Entity.where('source_id is not null').select([:system_id, :source_id, :name]).group_by(&:system_id)

{6=>
  [#<Obj name: "Lease", system_id: 6, source_id: "369">,
   #<Obj name: "Docks", system_id: 6, source_id: "864">,
   #<Obj name: "Marinas", system_id: 6, source_id: "1630">,
   #<Obj name: "Transporters", system_id: 6, source_id: "229">,
   #<Obj name: "Stations", system_id: 6, source_id: "83258">,
   #<Obj name: "Stations", system_id: 6, source_id: "2407">,
  ]}

我想把这个作为最终结果:

{6=> 
  {"369" => "Lease", "864" => "Docks", "1630" => "Marinas", "229" => "Transporters", "83258" => "Stations", "2407" => "Stations"} 
}

或者 :

{6=> 
  {"369" => #<Obj name: "Lease", system_id: 6, source_id: "369">, "864" => #<Obj name: "Docks", system_id: 6, source_id: "864">, "1630" => #<Obj name: "Marinas", system_id: 6, source_id: "1630">, "229" => #<Obj name: "Transporters", system_id: 6, source_id: "229">, "83258" => #<Obj name: "Stations", system_id: 6, source_id: "83258">, "2407" => #<Obj name: "Stations", system_id: 6, source_id: "2407">} 
}

哪个更容易生产。我基本上想用具有键 source_id 和值 obj 名称或整个对象的哈希替换对象数组。

我试过了 :

.each{|c_id, c| new_format = {c_id => {c.source_id => c} } }
NoMethodError: undefined method `source_id' for #<Array:0xb4bc4e4>

.each{|c_id, c| new_format = {c_id => c.group_by(&:source_id) } }
NameError: undefined local variable or method `new_format' for main:Object

还有其他几个选项,但我没有设法产生正确的结果。我怎样才能做到这一点?

4

2 回答 2

0
 # records is the hash returned by dbquery
 records.map{|k,v| records[k] = v.inject({}) {|hsh,obj| hsh[obj.source_id] = obj.name;hsh } }

这会将records散列修改为您想要的格式。

于 2013-09-19T09:43:47.897 回答
0

关于什么

top_hash.each { |key, array|
  top_hash[key] = array.each_with_object({}) { |obj, hash|
    hash[obj.source_id] = obj.name
  }
}
于 2013-09-19T09:43:59.200 回答