开发者

Array to nested hash

开发者 https://www.devze.com 2022-12-11 19:27 出处:网络
I have array of objects. I want to write method wich i will use such as this: group(array, :category, :month, year)

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
0

精彩评论

暂无评论...
验证码 换一张
取 消