Created
July 1, 2016 15:38
-
-
Save ProGM/e0401bf77e513a3abc187c1e79001732 to your computer and use it in GitHub Desktop.
Hash to Dotted Path
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
class HashToDottedPath | |
def initialize(hash) | |
@hash = hash | |
end | |
def to_dotted_path | |
result = [] | |
@hash.each do |k, v| | |
explore_keys(v, [k], result) | |
end | |
result.map! { |e| [e[0..-2].join('.'), e[-1]] }.to_h | |
end | |
private | |
def explore_keys(hash, state, list) | |
hash.each do |k, v| | |
s = state.dup | |
if v.is_a?(Hash) | |
s << k | |
explore_keys(v, s, list) | |
else | |
s << k << v | |
list << s | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment