Skip to content

Instantly share code, notes, and snippets.

@hyjk2000
Created August 18, 2016 06:16
Show Gist options
  • Select an option

  • Save hyjk2000/87977421512e2518f8d354719edd793e to your computer and use it in GitHub Desktop.

Select an option

Save hyjk2000/87977421512e2518f8d354719edd793e to your computer and use it in GitHub Desktop.
Depth-first traversal on a hash
h = {
foo: {
bar: {
baz: 1
},
oof: {
zab: 2
}
},
zha: {
liz: {
wng: 3,
qan: 4
}
}
}
def dft(hash)
path = []
return path unless hash.is_a? Hash
hash.each do |k, v|
path << k
path += dft(v)
end
path
end
p dft(h)
# [:foo, :bar, :baz, :oof, :zab, :zha, :liz, :wng, :qan]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment