我已经从directorylisting
对字符串进行了排序,并且需要使用嵌套的JSON。
输入:
/
/caseIH130SeriesbyStevie.zip/
/caseIH130SeriesbyStevie.zip/shaders
/caseIH130SeriesbyStevie.zip/shared
/caseIH1660byStevie.zip/
/caseIH1660byStevie.zip/shaders
/caseIH1660byStevie.zip/shared
/caseIH1660byStevie.zip/shared/lightPattern
预期输出
[
name: "/", children: [
name: "caseIH130SeriesbyStevie.zip", children: [
name: "shaders", children: [],
name: "shared", children: [] ],
name: "caseIH1660byStevie.zip", children: [
name: "shaders", children: [],
name: "shared", children: [] ],
# ...
我很难建立那个阵列。
第一级显然很容易。
if file == "/"
tree["root"][file] = {name: file, children: {}}
else
parent = file.path.split("/").reject!(&:blank?)
# ...
我的问题是,parent
是caseIH130SeriesbyStevie.zip
我可以和tree["root"][parent.first] =
一起去
但是如果父是2(或3)个元素长,如["caseIH130SeriesbyStevie.zip", "shaders"]
然后我需要访问tree["root"][parent.first][:children][parent.second] = {}
整个事情可能会有8个深度。
我是否想念一些东西或者那种困难?
将"a/b/c/d"
变为
["a", child: ["b", child: ["c", child: ["d", child: []]]]]
答案 0 :(得分:1)
它并不完美,但我认为它会有所帮助:
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 => []}]}]}]