Skip to content

Instantly share code, notes, and snippets.

@batasrki
Forked from quirkey/files_tree.rb
Created February 26, 2009 21:39
Show Gist options
  • Select an option

  • Save batasrki/71132 to your computer and use it in GitHub Desktop.

Select an option

Save batasrki/71132 to your computer and use it in GitHub Desktop.
# Given a class with an array of files as paths e.g.
# ['path/to/file.txt', 'other/file','path/file','file']
# Will organize them into a hash like
# {
# 'path' => {
# 'to' => {
# 'file' => {}
# },
# 'file' => {}
# },
# 'other' => {
# 'file' => {}
# },
# 'file' => {}
# }
require 'active_support'
# ...
def files_tree
tree = {}
files.each do |file|
split_dirs = file.split(/\//)
keyed_hash = {}
split_dirs.reverse.each do |key|
keyed_hash = {key => keyed_hash}
end
tree.deep_merge!(keyed_hash)
end
tree
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment