Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails + activerecord: how create a hash from table with particular field's value as key

Given a table ZipCodeInfos with fields zipcode, state, city (all strings), 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 entire table where the zipcode is a key like this:

{ "10000" => {:city => "Fooville", :state => "AA" },
"10001" => {:city => "Smallville", :state => "AA" },
"10002" => {:city => "Whoville", :state => "BB" } }

I know for a given record I can use .attributes to generate a hash with key,value pairs of field-names, field-values, for example Zipcode.first.attributes gives me

{"id" => 1, "zipcode" => "10000", "city" => "Fooville", "state => "AA" }

But, short of brute force iterating over each record (via .map), I cannot quite figure out how to create the desired hash with the zipcode as the key for each node of the hash.

This is the best I could come up with, and I suspect there is some nifty Ruby goodness that is faster?

zip_info_hash = {}
ZipCodeInfo.all.map{|x| zip_info_hash[x.zip] = 
                       {'state' => x.state, 'city' => x.city }}
like image 302
jpw Avatar asked Jul 11 '13 16:07

jpw


2 Answers

You could also try:

ZipCodeInfos.all.group_by &:zipcode 

will get you a hash of zip code to array of ZipCodeInfos activerecords.

like image 142
Tom Avatar answered Sep 28 '22 06:09

Tom


You can use inject method. Here is what I generally use.

def visitors_name_email
  visitors.inject({}) do |result, visitor|
    result.merge(visitor.name => visitor.email)
  end
end
like image 28
Addicted Avatar answered Sep 28 '22 08:09

Addicted