Given a ZipCodeInfos table with fields zipcode, state, city (all rows), where zipcode is unique:
zipcode,city,state "10000", "Fooville", "AA" "10001", "Smallville", "AA" "10002", "Whoville", "BB"
What is the fastest way to generate a hash object of the whole table, where zipcode is such a key:
{ "10000" => {:city => "Fooville", :state => "AA" }, "10001" => {:city => "Smallville", :state => "AA" }, "10002" => {:city => "Whoville", :state => "BB" } }
I know that for this record I can use. Zipcode.first.attributes to generate a hash with a key, pairs of field name values, field values, for example Zipcode.first.attributes gives me
{"id" => 1, "zipcode" => "10000", "city" => "Fooville", "state => "AA" }
But, with the exception of brute force, repeated across each record (via .map), I cannot figure out how to create the desired hash using zipcode as the key for each node hash.
Is this the best I could think of, and I suspect there is great ruby ββkindness that is faster?
zip_info_hash = {} ZipCodeInfo.all.map{|x| zip_info_hash[x.zip] = {'state' => x.state, 'city' => x.city }}