0

I am trying to create a nested hash from an array that has several elements saved to it. I've tried experimenting with each_with_object, each_with_index, each and map.

class Person
  attr_reader :name, :city, :state, :zip, :hobby
  def initialize(name, hobby, city, state, zip)
    @name = name
    @hobby = hobby
    @city = city
    @state = state
    @zip = zip
  end

end

steve = Person.new("Steve", "basketball","Dallas", "Texas", 75444)
chris = Person.new("Chris", "piano","Phoenix", "Arizona", 75218)
larry = Person.new("Larry", "hunting","Austin", "Texas", 78735)
adam = Person.new("Adam", "swimming","Waco", "Texas", 76715)

people = [steve, chris, larry, adam]

people_array = people.map do |person|
  person = person.name, person.hobby, person.city, person.state, person.zip
end

Now I just need to turn it into a hash. One issue I am having is, when I'm experimenting with other methods, I can turn it into a hash, but the array is still inside the hash. The expected output is just a nested hash with no arrays inside of it.

# Expected output ... create the following hash from the peeps array:
#
# people_hash = {
#   "Steve" => {
#     "hobby" => "golf",
#     "address" => {
#       "city" => "Dallas",
#       "state" => "Texas",
#       "zip" => 75444
#     }
#   # etc, etc

Any hints on making sure the hash is a nested hash with no arrays?

2 Answers 2

2

This works:

person_hash = Hash[peeps_array.map do |user|
  [user[0], Hash['hobby', user[1], 'address', Hash['city', user[2], 'state', user[3], 'zip', user[4]]]]
end]

Basically just use the ruby Hash [] method to convert each of the sub-arrays into an hash

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

Comments

1

Why not just pass people?

people.each_with_object({}) do |instance, h|
  h[instance.name] = { "hobby"   => instance.hobby,
                       "address" => { "city"  => instance.city,
                                      "state" => instance.state,
                                      "zip"   => instance.zip } }
end

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.