Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created March 9, 2010 13:25
Show Gist options
  • Save rklemme/326558 to your computer and use it in GitHub Desktop.
Save rklemme/326558 to your computer and use it in GitHub Desktop.
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