我试图从保存有几个元素的数组中创建嵌套散列。我尝试过试验each_with_object
,each_with_index
,each
和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
现在我只需要把它变成一个散列。我遇到的一个问题是,当我尝试其他方法时,我可以将它变成散列,但数组仍然在散列内。期望的输出只是一个嵌套的散列,其内部没有数组。
# Expected output ... create the following hash from the peeps array:
#
# people_hash = {
# "Steve" => {
# "hobby" => "golf",
# "address" => {
# "city" => "Dallas",
# "state" => "Texas",
# "zip" => 75444
# }
# # etc, etc
任何提示确保哈希是一个嵌套的哈希没有数组?
谢谢丹尼尔 - 非常有帮助! – user3604867 2014-10-29 22:13:08