How to convert a ruby hash with an 'array' key to a nested hash in Ruby?

Viewed 63

I'm trying to figure out how i can convert a complex hash like this:

{
  ["A", "B"]=>{"id"=>123,"name"=>"test"},
  ["A", "F"]=>{"id"=>236,"name"=>"another test"},
  ["C", "F"]=>{"id"=>238,"name"=>"anoother test"}
}

into an even more complex hash like

{
  "A"=>{
     "B"=>{"id"=>123,"name"=>"test"},
     "F"=>{"id"=>236,"name"=>"another test"}
  },
  "C"=>{
     "F"=>{"id"=>238,"name"=>"anoother test"}
  }
}

Any help would be really welcome!

2 Answers

each_with_object could be the rescue:

hash.each_with_object(Hash.new {|h, k| h[k] = {}}) do |((first, last), v), memo|  
  memo[first].merge!(last => v)
end
#=> {"A"=>{"B"=>{"id"=>123, "name"=>"test"}, 
#          "F"=>{"id"=>236, "name"=>"another test"}}, 
#    "C"=>{"F"=>{"id"=>238, "name"=>"anoother test"}}}
Related