DFS traversal of a deeply nested hash

2019-08-17 05:35发布

I have seen this question Traversing a Hash Recursively in Ruby

However I am still not able to achieve this. Can anyone please help (also explain).

Input hash:

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

I just need to traverse it and not search for anything

标签: ruby hash
1条回答
我命由我不由天
2楼-- · 2019-08-17 05:44

If all values are hashes, this would work:

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

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

traverse(hash)

Output:

0 .
1 foo
2 hello
2 world
1 bar
查看更多
登录 后发表回答