Created
December 20, 2012 17:22
-
-
Save geronimod/4346921 to your computer and use it in GitHub Desktop.
Snippet to translate a array of paths into a nested hash map
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
# ["home/folder1", "home/folder2", "home/folder1/folderA", "home/folder2/folderB"].as_paths_to_map | |
# => {"home"=>{"folder1"=>{"folderA"=>{}}, "folder2"=>{"folderB"=>{}}}} | |
class Array | |
def as_paths_to_map | |
auto_hash = Hash.new { |h,k| h[k] = Hash.new &h.default_proc } | |
self.each do |path| | |
sub = auto_hash | |
path.split( "/" ).each do |dir| | |
next if dir.empty? | |
sub = sub[dir] | |
end | |
end | |
auto_hash | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment