ruby 深度嵌套哈希的DFS遍历

ctzwtxfj  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(85)

我看过这个问题Traversing a Hash Recursively in Ruby
然而,我仍然无法做到这一点。有没有人可以帮忙(也可以解释一下)。
输入哈希:

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

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

polkgigr

polkgigr1#

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

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

def traverse(hash, depth = 0)
  hash.each do |key, value|
    puts "#{depth} #{key}"
    traverse(value, depth + 1)
  end
end

traverse(hash)

输出量:

0 .
1 foo
2 hello
2 world
1 bar

相关问题