7

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 }}

3 Answers 3

3

You could also try:

ZipCodeInfos.all.group_by &:zipcode 

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

I can't think of a way to avoid map here. I'd make only some minor changes to your code:

zip_info=Hash[*ZipCodeInfo.all
                          .map{|x| [x.zip, {:city => x.city, :state => x.state}]}
                          .flatten]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.