Skip to content

Instantly share code, notes, and snippets.

@railsfactory-pramod
Created July 5, 2012 19:03
Show Gist options
  • Save railsfactory-pramod/3055724 to your computer and use it in GitHub Desktop.
Save railsfactory-pramod/3055724 to your computer and use it in GitHub Desktop.
Tree traversal => Hash representing a tree
input = {"Root"=>[{"1"=>[{"4"=>"leaf4", "5"=>"leaf5"}]}, {"2"=>[{"6"=>"leaf6", "7"=>"leaf7"}]}]}
def traverse(path = "")
self.each do|key, value|
if value.is_a?(Hash)
path += "#{key}=>"
value.traverse(path)
else
if value.is_a?(Array)
path += "#{key}=>"
value.each do |val|
val.traverse(path)
end
else
puts "#{path}#{key}:#{value}"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment