Skip to content

Instantly share code, notes, and snippets.

@mamantoha
Last active March 4, 2019 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamantoha/6021290 to your computer and use it in GitHub Desktop.
Save mamantoha/6021290 to your computer and use it in GitHub Desktop.
Implementing a clone of *nix tree in Ruby
# encoding: utf-8
# Build a Hash tree from Array Of file names
#
def build_hash_tree(filenames)
files_tree = filenames.inject({}) { |h, i| t = h; i.split("/").each { |n| t[n] ||= {}; t = t[n] }; h }
end
# Box-drawing character - https://en.wikipedia.org/wiki/Box-drawing_character
# ├ └ ─ │
#
def display_tree(files_tree, level = -1, branches = [])
tab = ' ' * 4
level += 1
files_tree.each_with_index do |(key, val), index|
if val.empty? # this is a file
result = branches.take(level).inject('') { |s, i| s << (i == 1 ? '│ ': ' ') }
if index == files_tree.length - 1
# this is a last element
result << '└' + '── ' + key
else
result << '├' + '── ' + key
end
puts result
else # this is directory
if key == '' # root directory
result = '.'
else
result = branches.take(level).inject('') { |s, i| s << (i == 1 ? '│ ': ' ') }
if index == files_tree.length - 1
# this is a last element
result << '└' + '── ' + key
branches[level] = 0
else
result << '├' + '── ' + key
branches[level] = 1
end
end
puts result
# recursion \(^_^)/
display_tree(val, level, branches)
end
end
end
files = Dir['**/*']
# list/sort files before folders in a directory listing
files = files.map { |file| [file.count("/"), file] }
files = files.sort.reverse.map { |file| file[1] }
files_tree = build_hash_tree(files)
display_tree(files_tree)
$ ruby tree.rb
├── lib
│ ├── crowdin-api
│ │ ├── version.rb
│ │ ├── methods.rb
│ │ └── errors.rb
│ └── crowdin-api.rb
├── examples
│ ├── tree.rb
│ ├── project_info.rb
│ ├── directory_tree.rb
│ ├── Gemfile.lock
│ └── Gemfile
├── crowdin-api.gemspec
├── Rakefile
├── README.md
├── LICENSE
├── Gemfile.lock
└── Gemfile
@greyblake
Copy link

Nice) But whey just not to use tree ? 0_o

@mamantoha
Copy link
Author

This script was originally written to list the contents of directories in a tree-like format received from the external API (I had just an Array of file names). As I found out later this code is suitable for use with Dir.glob :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment