Gauthier Gauthier - 2 months ago 6
Ruby Question

Ruby hashes group by multiple value

I have multiple hashes who looks like this:

[{"name" => "name1", "folder" => "folder1", id => 1 },

{"name" => "name1", "folder" => "folder1", id => 2 },

{"name" => "name1", "folder" => "folder2", id => 3},

{"name" => "name2", "folder" => "folder1", id => 4}]


And my goal is to have something who looks like this:

{"name1" =>
[{"folder1" =>
[{"name" => "name1", "folder" => "folder1", id => 1 },
{"name" => "name1", "folder" => "folder1", id => 2 }] }
{"folder2" =>
[{"name" => "name1", "folder" => "folder2", id => 3}] }]

{"name2" =>
[{"folder 1" =>
[{"name" => "name2", "folder" => "folder1", id => 4}] }] }


I didn't find a proper solution who give exactly this kind or a similar result for now

Answer

This seems to do what you want:

transformed_hash = initial_hash
  .group_by { |x| x['name'] }
  .map { |k, v| [k, v.group_by{ |x| x['folder'] }] }
  .to_h