Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
input = {
'key1a.key2a.key3a' => 'value1',
'key1a.key2b.key3b' => 'value2',
'key1a.key2c.key3c' => 'value3',
'key1a.key2c.key3d' => 'value4'
def flat_keys_to_nested(hash)
hash.each_with_object({}) do |(key,value), all|
key_parts = key.split('.')
leaf = key_parts[0...-1].inject(all) { |h, k| h[k] ||= {} }
leaf[key_parts.last] = value
puts flat_keys_to_nested(input)
# {"key1a"=>{"key2a"=>{"key3a"=>"value1"}, "key2b"=>{"key3b"=>"value2"}, "key2c"=>{"key3c"=>"value3", "key3d"=>"value4"}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.