Array to nested hash
I have array of objects. I want to write method wich i will use such as this:
group(array, :category, :month, year)
and will return me a Hash such as this:
{ 'some category => { '2009' => { '01' => [objects], '02 => [objects2]code } } }
This should work simmilar to group_by, but I haven o idea to do that. I don't know how to handle number of group params. I can group group(array, :category)
or group(array, :a, :b, :c, :d, :e)
Any help?
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
精彩评论