2014-10-29 110 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