假设我们有以下对象:
foo = {
a: '1.0',
children: [
{
a: '1.1',
children: [
{
a: '1.1.1',
children: []
},
{
a: '1.1.2',
children: [
{ a: '1.1.2.1' , children: [] }
]
},
{
a: 1.2,
children: [
{
a: '1.2.1',
children: []
}
]
}
]
}
]
}
这里是副本的链接:https://repl.it/repls/ForkedThistleObjectmodel。任务是递归地遍历所有子对象并打印a
键的值。谢谢。
似乎只有递归版本,看起来像这样:
def step(obj, level = 0)
p "Current: level - #{level}; a: #{obj[:a]}"
obj[:children].each do |item|
step(item, level + 1)
end
end
step(foo)
这里是a repl link
[就像其他海报提到的那样,您期望输出什么?如果您想要这样的东西:
a=>1.0
a=>1.1
a=>1.1.1
a=>1.1.2
a=>1.1.2.1
a=>1.2
a=>1.2.1
要将值打印到标准输出,则可以尝试两个递归函数。
def display_foo_aux(f)
f.each{|e|
display_foo(e)
}
end
def display_foo(f)
f.each{|k, v|
if k == :children
display_foo_aux(v)
else
puts "#{k}=>#{v}"
end
}
end
display_foo(foo)
如果需要生成值列表,则需要累积元素。