1

This code:

@countries.map { |l| [l.country_name, l.latitude, l.longitude, l.capital] }

returns

[["country_name_1", latitude, longitude, capital],["country_name_2", latitude, longitude, capital],...]

But I need to convert to JSON; something like this:

{
   "country_name_1" : [latitude, longitude, "capital"],
   "country_name_2" : [latitude, longitude, "capital"],
   .
   .
   .
}

1 Answer 1

4

This should work:

Hash[@countries.map { |l| [l.country_name, [l.latitude, l.longitude, l.capital]] }]

Rails also provides index_by:

@countries.index_by(&:country_name)
# => {
#      "country_name_1" => #<Country latitude:..., longitude:...>,
#      "country_name_2" => #<Country latitude:..., longitude:...>,
#    }

Objects might be more convenient than hashes.

Regarding JSON

Rails has built-in support for JSON: http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-json

You can also call to_json manually:

hash = Hash[@countries.map { |l| [l.country_name, [l.latitude, l.longitude, l.capital]] }]
hash.to_json

Or use the JSON Builder gem.

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

2 Comments

This returns, country_name = [...] but I need country_name : [...]
Do you need a Ruby hash or something like JSON?

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.