2009-11-12 288 views
0

我有對象數組。我想寫方法至極,我將使用像這樣的: group(array, :category, :month, year) 並返回我一個哈希像這樣:嵌套散列數組

 
{ 
    'some category => { 
    '2009' => { 
     '01' => [objects], 
     '02 => [objects2]code 
    } 
    } 
} 

這應該工作simmilar到GROUP_BY,但還沒Ø想法做。我不知道如何處理組參數的數量。我可以組group(array, :category)group(array, :a, :b, :c, :d, :e)

任何幫助嗎?

回答

2
def group(array, *levels) 
    groups = {} 
    last = levels.pop 
    array.each do |obj| 
    curr = groups 
    levels.map {|level| obj.send(level) rescue nil }.each {|val| curr = (curr[val] ||= {}) } 
    idx = obj.send(last) rescue nil 
    (curr[idx] ||= []) << obj 
    end 
    groups 
end