Created
August 18, 2016 06:16
-
-
Save hyjk2000/87977421512e2518f8d354719edd793e to your computer and use it in GitHub Desktop.
Depth-first traversal on a hash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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