遍历数组以创建嵌套哈希 [英] Iterating over an array to create a nested hash

查看:91
本文介绍了遍历数组以创建嵌套哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一个保存有多个元素的数组中创建一个嵌套哈希.我已经尝试过使用each_with_objecteach_with_indexeachmap.

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?

推荐答案

这有效:

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]

基本上只使用ruby 哈希[]方法将每个子数组转换为哈希

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

这篇关于遍历数组以创建嵌套哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆