From: Adam Shelly Date: 2008-02-12T09:24:12+09:00 Subject: Re: nested hash from array of paths On 2/11/08, Adam Groves wrote: > array = ["home", "about", "about/history", "about/company", > "about/history/part1", "about/history/part2"] > > I want to build a tree from this array in the form of a nested hash: > > > {"home" => nil, "about => {"history => ["part1" => nil, "part2" => > nil]", "company" => nil}} > > Any ideas as to how best to solve this? > I could only figure out how to do it using 2 passes: tree ={} array.sort.each{|w| h=tree w.split('/').each{|part| h=h[part]||=Hash.new} } def cleanup h return true if h.empty? h.find_all{|k,v|h[k]=nil if v.is_a?(Hash)&&cleanup(v)} false end cleanup tree p tree => {"about"=>{"company"=>nil, "history"=>{"part1"=>nil, "part2"=>nil}}, "home"=>nil} -Adam