Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DFS in nested Hashes
#! ruby19
require 'pp'
Converter = Struct.new :root, :converted do
def convert
@stack = []
self.converted = {}
dfs(root)
self.converted
end
private
def dfs(n)
case n
when Hash
n.each do |k,v|
@stack.push k
dfs(v)
@stack.pop
end
else
converted[@stack.join(' ')] = n
end
end
end
conv = Converter.new("a"=>{"b"=>{"c"=>1}, "b2"=>{"c2"=> {"d2" => 2}}})
conv.convert
pp conv.converted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment