我有一个数组:
issues={#<Issue id: 669, tracker_id: 2,parent_id: 663,
#<Issue id: 668, tracker_id: 2, parent_id: 663,
#<Issue id: 667, tracker_id: 2, parent_id: 665,
#<Issue id: 666, tracker_id: 2, parent_id: 665,
#<Issue id: 665, tracker_id: 2, parent_id: 658,
#<Issue id: 664, tracker_id: 2, parent_id: 662,
#<Issue id: 663, tracker_id: 2, parent_id: 662,
#<Issue id: 662, tracker_id: 2, parent_id: 658,
#<Issue id: 661, tracker_id: 2, parent_id: nil}]
如果我使用group_by
:
leveled_tasks = issues.sort_by(&:id).group_by(&:parent)
我得到以下结果:
{ nil=>[#<Issue id: 661, tracker_id: 2, parent_id: nil}],
658=>[#<Issue id: 665, tracker_id: 2, parent_id: 658,
#<Issue id: 662, tracker_id: 2, parent_id: 658],
662=>[#<Issue id: 664, tracker_id: 2, parent_id: 662,
#<Issue id: 663, tracker_id: 2, parent_id: 662],
663=>[#<Issue id: 669, tracker_id: 2,parent_id: 663,
#<Issue id: 668, tracker_id: 2, parent_id: 663],
665=>[#<Issue id: 667, tracker_id: 2, parent_id: 665,
#<Issue id: 666, tracker_id: 2, parent_id: 665]}
我想要它:
{ 0=>[#<Issue id: 661, tracker_id: 2, parent_id: nil}],
1=>[#<Issue id: 665, tracker_id: 2, parent_id: 658,
#<Issue id: 662, tracker_id: 2, parent_id: 658],
2=>[#<Issue id: 664, tracker_id: 2, parent_id: 662,
#<Issue id: 663, tracker_id: 2, parent_id: 662],
3=>[#<Issue id: 669, tracker_id: 2,parent_id: 663,
#<Issue id: 668, tracker_id: 2, parent_id: 663],
4=>[#<Issue id: 667, tracker_id: 2, parent_id: 665,
#<Issue id: 666, tracker_id: 2, parent_id: 665]}
我使用group_by level
,但它给了我:
NoMethodError (undefined method level' for #<Issue:0xb514796c>): lib/redmine/sudo_mode.rb:63:in sudo_mode'
为此:
leveled_tasks = issues.sort_by(&:id).group_by(&:level)
答案 0 :(得分:0)
您可以循环哈希键并开始填充一个具有所需输出的新键,如:
grouped_issues = issues.sort_by(&:id).group_by(&:parent)
leveled_tasks = {}
grouped_issues.keys.each_with_index do |key, index|
leveled_tasks[index] = grouped_issues[key]
end