Skip to content

Instantly share code, notes, and snippets.

@geronimod
Created December 20, 2012 17:22
Show Gist options
  • Save geronimod/4346921 to your computer and use it in GitHub Desktop.
Save geronimod/4346921 to your computer and use it in GitHub Desktop.
Snippet to translate a array of paths into a nested hash map
# ["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