huan son huan son - 1 month ago 15
Ruby Question

build multi associated array with unknown depth

I have sorted strings from a

directorylisting
and need to make nested JSON out of it.

Input:

/
/caseIH130SeriesbyStevie.zip/
/caseIH130SeriesbyStevie.zip/shaders
/caseIH130SeriesbyStevie.zip/shared
/caseIH1660byStevie.zip/
/caseIH1660byStevie.zip/shaders
/caseIH1660byStevie.zip/shared
/caseIH1660byStevie.zip/shared/lightPattern


Expected output

[
name: "/", children: [
name: "caseIH130SeriesbyStevie.zip", children: [
name: "shaders", children: [],
name: "shared", children: [] ],
name: "caseIH1660byStevie.zip", children: [
name: "shaders", children: [],
name: "shared", children: [] ],

# ...


I struggle building up that array.

First level is obviously easy.

if file == "/"
tree["root"][file] = {name: file, children: {}}
else
parent = file.path.split("/").reject!(&:blank?)
# ...


My problem here is, that
parent
is
caseIH130SeriesbyStevie.zip

i can go with
tree["root"][parent.first] =

but what if parent is 2 (or 3) elements long , like
["caseIH130SeriesbyStevie.zip", "shaders"]


I then need to access
tree["root"][parent.first][:children][parent.second] = {}

the whole thing can go probpably 8 levels deep.

Do i miss something or is that kind of difficult ?

Summary / tl;dr



turn
"a/b/c/d"
into
["a", child: ["b", child: ["c", child: ["d", child: []]]]]

Answer

It's not perfect but I think it can be helpful :

class TakeSubs
    def initialize(string)
        @arr = string.split('/')
    end

    def get_it(i=0)
        element = @arr[i]
        if element 
            [element, Hash[:child, get_it(i+1)]]
        else
            []
        end
    end

end 

res = TakeSubs.new('a/b/c')
p res.get_it
 #=> ["a",  {:child => ["b",  {:child => ["c", {:child => []}]}]}]