Skip to content

Instantly share code, notes, and snippets.

@jelder
Last active August 29, 2015 14:01
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 jelder/5d42653740205e447c80 to your computer and use it in GitHub Desktop.
Save jelder/5d42653740205e447c80 to your computer and use it in GitHub Desktop.
Hash insertion by path
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