Last active
August 29, 2015 14:11
-
-
Save jelder/736aa3e2656ce25aebb6 to your computer and use it in GitHub Desktop.
Extend Hash to allow insertion by path
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
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