Iterating over an array to create a nested hash

大兔子大兔子 提交于 2019-12-25 04:01:47

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/26641210/iterating-over-an-array-to-create-a-nested-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!