Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将整数和对象数组的哈希映射到其他格式_Ruby On Rails_Ruby_Arrays_Hash - Fatal编程技术网

Ruby on rails 将整数和对象数组的哈希映射到其他格式

Ruby on rails 将整数和对象数组的哈希映射到其他格式,ruby-on-rails,ruby,arrays,hash,Ruby On Rails,Ruby,Arrays,Hash,我有我的散列的这种格式,我使用这个实体从数据库中获取。其中('source\u id不为null')。选择([:system\u id,:source\u id,:name])。分组人(&:system\u id): 或: 还有几个其他的选择,但我没有得到正确的结果。我该怎么做 # records is the hash returned by dbquery records.map{|k,v| records[k] = v.inject({}) {|hsh,obj| hsh[obj.sou

我有我的散列的这种格式,我使用这个
实体从数据库中获取。其中('source\u id不为null')。选择([:system\u id,:source\u id,:name])。分组人(&:system\u id)

或:

还有几个其他的选择,但我没有得到正确的结果。我该怎么做

 # records is the hash returned by dbquery
 records.map{|k,v| records[k] = v.inject({}) {|hsh,obj| hsh[obj.source_id] = obj.name;hsh } }
这会将
记录
哈希修改为您所需的格式。

怎么样

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

这里的地图使用得很好。@tihom这张地图很好地映射了内部地图,即
{“369”=>“租赁”、“864”=>“码头”、“1630”=>“码头”、“229”=>“运输者”、“83258”=>“车站”、“2407”=>“车站”}
但我缺少
6=>
父键此调用将修改记录哈希值<代码>记录={6=>{“369”=>“租赁”,“864”=>“码头”…},…}
{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">} 
}
.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
 # records is the hash returned by dbquery
 records.map{|k,v| records[k] = v.inject({}) {|hsh,obj| hsh[obj.source_id] = obj.name;hsh } }
top_hash.each { |key, array|
  top_hash[key] = array.each_with_object({}) { |obj, hash|
    hash[obj.source_id] = obj.name
  }
}