Created
September 29, 2015 13:25
-
-
Save yuriihabrusiev/50a689f45599ee7985b9 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
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 | |
end | |
end | |
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