2014-10-29 40 views
0

我试图从保存有几个元素的数组中创建嵌套散列。我尝试过试验each_with_object,each_with_index,eachmap迭代数组以创建嵌套散列

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 

任何提示确保哈希是一个嵌套的哈希没有数组?

回答

1

这工作:

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] 

基本上只是使用红宝石Hash [] method到每个子阵列转换成散列

+0

谢谢丹尼尔 - 非常有帮助! – user3604867 2014-10-29 22:13:08

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