Last active
December 29, 2017 23:42
-
-
Save lukaszx0/e6fc50fdbfca82ae5557dda05569be75 to your computer and use it in GitHub Desktop.
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 Hash | |
def flatten_with_dotted_keys(&block) | |
stack = [] | |
flattened = {} | |
flatten_dfs(self, stack, flattened, block) | |
flattened | |
end | |
private | |
def flatten_dfs(elem, stack, flattened, block) | |
case elem | |
when Hash | |
elem.each do |key, val| | |
stack.push(key) | |
flatten_dfs(val, stack, flattened, block) | |
stack.pop | |
end | |
else | |
flattened[stack.join('.')] = block.is_a?(Proc) ? block.call(elem) : elem | |
end | |
end | |
end | |
puts ({"foo" => "bar", "a"=>{"b"=>{"c"=>1}, "b2"=>{"c2"=> {"d2" => 2}}}}).flatten_with_dotted_keys.inspect | |
puts ({"foo" => "bar", "a"=>{"b"=>{"c"=>1}, "b2"=>{"c2"=> {"d2" => 2}}}}).flatten_with_dotted_keys { |e| e.to_s+"_suffix" }.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment