给定一个表 ZipCodeInfos,其中包含字段 zipcode、state、city(所有字符串),其中 zipcode 是唯一的:
zipcode,city,state
"10000", "Fooville", "AA"
"10001", "Smallville", "AA"
"10002", "Whoville", "BB"
生成整个表的哈希对象的最快方法是什么,其中邮政编码是这样的键:
{ "10000" => {:city => "Fooville", :state => "AA" },
"10001" => {:city => "Smallville", :state => "AA" },
"10002" => {:city => "Whoville", :state => "BB" } }
我知道对于给定的记录,我可以使用 .attributes 生成带有键、值对的字段名、字段值对的哈希,例如Zipcode.first.attributes
给我
{"id" => 1, "zipcode" => "10000", "city" => "Fooville", "state => "AA" }
但是,没有暴力迭代每条记录(通过.map),我无法完全弄清楚如何使用邮政编码作为散列每个节点的键来创建所需的散列。
这是我能想到的最好的,我怀疑有一些漂亮的 Ruby 优点更快?
zip_info_hash = {}
ZipCodeInfo.all.map{|x| zip_info_hash[x.zip] =
{'state' => x.state, 'city' => x.city }}