DFS遍历深度嵌套的哈希

我已经看到这个问题在Ruby中递归遍历哈希

但是我仍然无法做到这一点。 任何人都可以请帮助(也解释)。

输入哈希:

{"." => {"foo" => {"hello" => {}, "world" => {}}, "bar" => {}}} 

我只需要遍历它而不是搜索任何东西

如果所有值都是哈希值,那么这将起作用:

 hash = {"." => {"foo" => {"hello" => {}, "world" => {}}, "bar" => {}}} def traverse(hash, depth = 0) hash.each { |key, value| puts "#{depth} #{key}" traverse(value, depth + 1) } end traverse(hash) 

输出:

 0 . 1 foo 2 hello 2 world 1 bar