简体   繁体   中英

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

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!

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"}}}

You can also use Enumerable#group_by then Hash#transform_values by Enumerable#map to a new hash using Array#to_h :

h.group_by { |h,k| h.first }.transform_values { |v| v.map { |a, b| [a.last, b] }.to_h }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM