Skip to content

Instantly share code, notes, and snippets.

@AquisTech
Last active April 2, 2016 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AquisTech/c82d3ef9563a3126a93d61a71519f2a1 to your computer and use it in GitHub Desktop.
Save AquisTech/c82d3ef9563a3126a93d61a71519f2a1 to your computer and use it in GitHub Desktop.
explode_dotted_keys.rb
require 'ap'
module HashExt
def explode_keys(key_delimiter: '.')
recursive_hash = self.class.new { |hash, key| hash[key] = self.class.new(&hash.default_proc) }
result = self.to_h.reduce(recursive_hash) do |recursive_acc, (input_key_path, input_value)|
keys = input_key_path.to_s.split(key_delimiter)
tree = keys.map {|key| [:[], key] }
tree.push([:[]=, tree.pop[1], input_value])
tree.reduce(recursive_acc) do |acc, tree_node|
acc.public_send(tree_node.shift, *tree_node)
end
recursive_acc
end
result.default = self.class.new.default
result
end
def explode_keys!(key_delimiter: '.') # TODO - Make it working
puts self.methods.sort
# self = explode_keys(key_delimiter)
end
end
class Hash
include HashExt
end
class HashWithIndifferentAccess
include HashExt
end
ap h = {
'a.b1.c1' => 'ab1c1',
'a.b1.c2' => 'ab1c2',
# 'a' => {'b3' => 'a.b3', 'b4.f1' => 'a.b4.f1'},
'a.b2.d1.e2' => 'a.b2.d1.e2',
'a.b4.f2' => 'a.b4.f2',
'a.b2.d1.e1' => 'a.b2.d1.e1',
}
# n = h.explode_dotted_keys
#
n = h.explode_keys
ap n
h.explode_keys!
ap h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment