我有一个字符串 "Animals ( Reptiles Birds ( Eagles Pigeons Crows ) )"
我需要返回:
a = [
{
"Animals" => [
{
"Reptiles" => nil
},
{
"Birds" => [
{ "Eagles" => nil },
{ "Pigeons" => nil },
{ "Crows" => nil }
]
}
]
}
]
我不明白我该怎么做。 我在哪里可以找到一些例子或者我可以在谷歌中搜索什么?
最佳答案
这是将字符串转换为数组的一种方法。
代码
def arrayify(arr)
a = split_arr(arr)
a.map do |h|
k = h.keys.first
v = h.values.first
case v
when Array then { k => arrayify(v) }
else { k=>v }
end
end
end
def split_arr(arr)
a = []
while arr.any?
word = arr.shift
if arr.empty? || arr.first != ?(
a << { word=>nil }
else
arr.shift
close_count = 0
b = []
loop do
token = arr.shift
case token
when ?)
break if close_count == 0
close_count -= 1
when ?( then close_count += 1
end
b << token
end
a << { word=>b }
end
end
a
end
示例
str = "Animals ( Reptiles Birds ( Eagles Pigeons Crows ) ) Foods ( " +
"Snacks Breakfast ( Pancakes Waffles ) )"
arrayify(str.split)
#=> [{"Animals"=>[{"Reptiles" =>nil},
# {"Birds" =>[{"Eagles" =>nil},
# {"Pigeons"=>nil},
# {"Crows" =>nil}
# ]
# }
# ]
# },
# {"Foods" =>[{"Snacks" =>nil},
# {"Breakfast"=>[{"Pancakes"=>nil},
# {"Waffles" =>nil}
# ]
# }
# ]
# }
# ]
关于ruby - 将带括号的字符串转换为树,Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27338031/