2

I have this array of hashes that was created when a did a API call and ran it through JSON.parse:

{
  "results": [
    {
      "zip": "08225",
      "city": "Northfield",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "0.0"
    },
    {
      "zip": "08221",
      "city": "Linwood",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "1.8"
    }
  ]
}

I am trying to get all the zipcodes out of each object and put them into an array:

zipcode_array = Array.new

I have tried the following code:

locations.each do |zipcode|
    zipcode_array.push(['results'][i]['zip'])
end

I would like my final output to be:

zipcode_array = ["08225", "08221"]

Anyone have any tips on what I'm missing?

1
  • Tip: Instead of the verbose Java style Array.new you can do [ ] in Ruby to make a new, empty array. Array.new is saved for special occasions like Array.new(10,0) when you want an array with a particular pre-defined size and (optional) default. Commented Apr 15, 2018 at 7:50

2 Answers 2

7

Your code seems to lack i variable (index) here, but actually you don't need it, since you can always use map function to achieve idiomatic Ruby code:

require "json"

response = '{
  "results": [
    {
      "zip": "08225",
      "city": "Northfield",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "0.0"
    },
    {
      "zip": "08221",
      "city": "Linwood",
      "county": "Atlantic",
      "state": "NJ",
      "distance": "1.8"
    }
  ]
}'

parsed_response = JSON.parse(response)
zipcode_array = parsed_response["results"].map { |address| address["zip"] }
Sign up to request clarification or add additional context in comments.

Comments

3

instead of using each you can use map function to achieve this.

response[:results].map{|x| x[:zip]}

This will give you the result in array i.e

["08225", "08221"]

3 Comments

You are iterating the one by one
yes right. Thanks for pointing out the word iterating. edited my answer for the same. map will give you the new array instead of creating a new one and push into it.
This is generally the right idea, but JSON hashes will have only string keys, never symbols, at least not without conversion.

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.