A command line printer of tree structures (e.g. directory tree) written in Ruby.
This library can be used to build a tree structure, and render or print it like an ASCII graph.
e.g. it can be used to implement a directory tree printer just like the Linux utility tree. See bin/tree.rb
gem install cli-tree
require 'cli-tree'
- Create a TreeNode:
tree = TreeNode.new(node_name, children = [])
- Add more TreeNode objects to
children
:tree.children << child_node
- Add more TreeNode objects to
child_node
, and so on. - Call
puts tree.render
ortree.print
to print the tree.
TreeNode methods:
initialize(name, children = [])
TreeNode.from_h(hash)
: hash is{name: "string", children: [hash1, ...]}
TreeNode.from_json(json)
: similar tofrom_h
to_h
: convert TreeNode to Hashto_json(**kwargs)
: kwargs refer to JSON#generaterender
: draw an ASCII tree graphprint(stream: STDOUT, prefix: '')
: puts the rendered text to a stream
require 'cli-tree'
# the tree and all nodes are TreeNode objects
tree = TreeNode.new("root", [
TreeNode.new("foo", [
TreeNode.new("bar"),
TreeNode.new("baz"),
])
])
puts tree.render
or build the tree from a Hash or JSON:
require 'cli-tree'
data = {
name: "root", # every node must have a name
children: [ # and an optional children array
{ # non-leaf child must be a Hash
name: "foo",
children: [
"bar", # leaf child can be a String
"baz",
],
},
],
}
tree = TreeNode.from_h(data)
tree.print
Output:
root
└── foo
├── bar
└── baz