DFS traversal of a deeply nested hash

2019-08-17 05:26发布

问题:

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

回答1:

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


标签: ruby hash