我有以下深层嵌套的ruby对象的有序哈希:
{
#<Post:0x007f8a3dcc3980
id: 1,
title: "Title 1",
created_at: Wed, 10 Jun 2015 05:49:27 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:27 EDT -04:00>=>{
#<Post:0x007f8a3dc735e8
id: 7,
title: "Title 1",
created_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00>=>{},
#<Post:0x007f8a3dc4bea8
id: 5,
title: "Title 2",
created_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00>=>{},
#<Post:0x007f8a3dc3b760
id: 4,
title: "Title 3",
created_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00>=>{},
#<Post:0x007f8a3bd68d60
id: 3,
title: "Title 4",
created_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00>=>{},
#<Post:0x007f8a3db63928
id: 9,
title: "Title 5",
created_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:31 EDT -04:00>=>{}
},
#<Post:0x007f8a3dcc2c88
id: 10,
title: "Title 2",
created_at: Wed, 10 Jun 2015 05:49:27 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:27 EDT -04:00>=>{},
#<Post:0x007f8a3dcc2c88
id: 13,
title: "Title 3",
created_at: Wed, 10 Jun 2015 05:49:27 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:27 EDT -04:00>=>{},
#<Post:0x007f8a3dcc2c88
id: 18,
title: "Title 4",
created_at: Wed, 10 Jun 2015 05:49:27 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:27 EDT -04:00>=>{
#<Post:0x007f8a3dc83358
id: 11,
title: "Title 1",
created_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00>=>{
#<Post:0x007f8a3c21c708
id: 20,
title: "Title 1",
created_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00>=>{
#<Post:0x007f8a3c21c708
id: 24,
title: "Title 1",
created_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00>=>{},
},
},
},
#<Post:0x007f8a3c21c708
id: 12,
title: "Title 5",
created_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00>=>{},
#<Post:0x007f8a3c216f38
id: 16,
title: "Title 6",
created_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00>=>{},
#<Post:0x007f8a3bd7ab28
id: 17,
title: "Title 7",
created_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00,
updated_at: Wed, 10 Jun 2015 05:49:30 EDT -04:00>=>{}
}
我尝试做的是构建这些对象的平面列表,其中一些格式表示散列中每个对象的深度。即:
Title 1
- Title 1
- Title 2
- Title 3
- Title 4
- Title 5
Title 2
Title 3
Title 4
- Title 1
-- Title 1
--- Title 1
Title 5
Title 6
Title 7
我已经尝试了一个迭代每个哈希级别的函数,并为它下降的每个深度增加一个变量。问题是它最终会像这样:
Title 1
- Title 1
- Title 2
- Title 3
- Title 4
- Title 5
- Title 2
- Title 3
- Title 4
-- Title 1
--- Title 1
---- Title 1
---- Title 5
---- Title 6
---- Title 7
如果我能确定散列中每个单独对象的深度,那会好得多。有谁知道我怎么能做到这一点?
使用当前方法更新:
def iterate_hash(hash)
hash.each do |hash|
"#{dash_level} #{hash[0][:name]}",
hash[0][:id]
next if hash[1].blank?
dash_level = dash_level + '-'
iterate_hash(hash[1])
end
end