Last active
August 29, 2015 14:01
-
-
Save jelder/5d42653740205e447c80 to your computer and use it in GitHub Desktop.
Hash insertion by path
This file contains 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
require 'ap' | |
class Hash | |
def store_by_path(path, value) | |
case path | |
when String | |
if path =~ %r{/} | |
store_by_path(path.split('/'), value) | |
else | |
self[path] = value | |
end | |
when Array | |
key = path.shift | |
if path.empty? | |
self[key] = value | |
else | |
self[key] ||= self.class.new | |
self[key].store_by_path(path, value) | |
end | |
end | |
end | |
end | |
hash = {} | |
hash.store_by_path("outer/something/first", "hello, world") | |
hash.store_by_path(%w[outer something second], "bonjour") | |
hash.store_by_path(%w[outer something last], "hola") | |
hash.store_by_path(%w[outer surprise another hash], :deep) | |
ap hash | |
# { | |
# "outer" => { | |
# "something" => { | |
# "first" => "hello, world", | |
# "second" => "bonjour", | |
# "last" => "hola" | |
# }, | |
# "surprise" => { | |
# "another" => { | |
# "hash" => :deep | |
# } | |
# } | |
# } | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment