Skip to content

Instantly share code, notes, and snippets.

@jelder
Last active August 29, 2015 14:11
Show Gist options
  • Save jelder/736aa3e2656ce25aebb6 to your computer and use it in GitHub Desktop.
Save jelder/736aa3e2656ce25aebb6 to your computer and use it in GitHub Desktop.
Extend Hash to allow 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
def fetch_by_path(path)
case path
when String
if path =~ %r{/}
fetch_by_path(path.split('/'))
else
return self[path]
end
when Array
key = path.shift
if path.empty?
return self[key]
else
self[key].fetch_by_path(path)
end
end
end
end
hash = {}
puts "Storing"
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
puts "Fetching"
ap hash.fetch_by_path("outer/something/first")
ap hash.fetch_by_path(%w[outer something second])
ap hash.fetch_by_path(%w[outer something last])
ap hash.fetch_by_path(%w[outer surprise another 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