2

I have this array of paths:

[
 "Shape Up.Introduction.Growing Pains",
 "Shape Up.Shaping.Principles of Shaping.Wireframes are too concrete",
 "Shape Up.Shaping.Principles of Shaping.Words are too abstract",
 "Shape Up.Introduction.Six-week cycles",
 "Shape Up.Shaping.Steps to shaping"
]

Each segment is separated with a ..

I need to render a Table of Contents in the view.

What's the simplest way to transform the array into a nested hash? Or perhaps there's a better structure / approach to generate the required html out of this?

UPD

[
 "Shape Up.Introduction.Growing Pains",
 "Shape Up.Shaping.Principles of Shaping.Wireframes are too concrete",
 "Shape Up.Shaping.Principles of Shaping.Words are too abstract",
 "Shape Up.Introduction.Six-week cycles",
 "Shape Up.Shaping.Steps to shaping"
].inject({}) {|h,i|
  t = h; i.split(".").each {|n| t[n] ||= {}; t = t[n]}; h
}

Gives a hash tree structure that I need:

{
    "Shape Up" => {
        "Introduction" => {
              "Growing Pains" => {},
            "Six-week cycles" => {}
        },
             "Shaping" => {
            "Principles of Shaping" => {
                "Wireframes are too concrete" => {},
                     "Words are too abstract" => {}
            },
                 "Steps to shaping" => {}
        }
    }
}
Adam
  • 101
  • 1
  • 7

0 Answers0