将整数和对象数组的散列映射到其他格式

时间:2013-09-19 09:34:19

标签: ruby-on-rails ruby arrays hash

我有这种哈希格式,我使用这个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 name或整个对象。

我试过了:

.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

还有其他几种选择,但我没有设法产生正确的结果。我怎么能这样做?

2 个答案:

答案 0 :(得分: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哈希值修改为您想要的格式。

答案 1 :(得分:0)

怎么样?
top_hash.each { |key, array|
  top_hash[key] = array.each_with_object({}) { |obj, hash|
    hash[obj.source_id] = obj.name
  }
}