Phrogz
2/12/2008 5:00:00 AM
On Feb 11, 4:43 pm, Adam Groves <adam.gro...@gmail.com> wrote:
> Hi,
>
> I'm banging my head against the wall with the following problem:
>
> 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}}
Your output doesn't seem consistent. (Why an array sometimes but a
hash others?)
Here's something simple and close:
array = ["home", "about", "about/history", "about/company", "about/
history/part1", "about/history/part2"]
auto_hash = Hash.new{ |h,k| h[k] = Hash.new &h.default_proc }
array.each{ |path|
sub = auto_hash
path.split( "/" ).each{ |dir| sub[dir]; sub = sub[dir] }
}
p auto_hash
#=> {"about"=>{"company"=>{}, "history"=>{"part1"=>{}, "part2"=>{}}},
"home"=>{}}