迭代数组以创建嵌套哈希

时间:2014-10-29 21:45:14

标签: ruby hash

我正在尝试从保存了多个元素的数组创建嵌套哈希。我尝试过each_with_objecteach_with_indexeachmap

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

现在我只需要把它变成哈希。我遇到的一个问题是,当我在尝试其他方法时,我可以把它变成一个哈希,但是数组仍然在哈希中。预期的输出只是一个嵌套的哈希,里面没有数组。

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

确保散列是没有数组的嵌套散列的任何提示?

2 个答案:

答案 0 :(得分:2)

这有效:

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 Hash [] method将每个子数组转换为哈希

答案 1 :(得分:1)

为什么不通过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