Skip to content

Instantly share code, notes, and snippets.

@lukaszx0
Last active December 29, 2017 23:42
Show Gist options
  • Save lukaszx0/e6fc50fdbfca82ae5557dda05569be75 to your computer and use it in GitHub Desktop.
Save lukaszx0/e6fc50fdbfca82ae5557dda05569be75 to your computer and use it in GitHub Desktop.
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