unsorted_tree is a thin gem to abstract unsorted trees through single nodes.
- Ruby >= 1.9.3
Add this line to your application's Gemfile:
gem 'unsorted_tree', github: 'thisisdmg/unsorted_tree'
And then execute:
$ bundle install
node = UnsortedTree::Node.new
# with content
node = UnsortedTree::Node.new(Object.new)
node.content # => #<Object>
child = UnsortedTree::Node.new
node.add(child)
# or
child = node.add(UnsortedTree::Node.new)
# or
child = node.add
root = UnsortedTree::Node.new
child = root.add
root.children # => #<Set: {child}>
node.parent # => root
root = UnsortedTree::Node.new
child = root.add
child.root # => root
root = UnsortedTree::Node.new
child_1 = root.add
child_2 = root.add
child_1.siblings # => #<Set: {child_2}>
root = UnsortedTree::Node.new
child = root.add
grand_child = child.add
grand_child.ancestors # => [root, child], ordered by depth, root node first
root = UnsortedTree::Node.new
child = root.add
root.ancestor_of?(child) # => true
child.ancestor_of?(root) # => false
root = UnsortedTree::Node.new
child = root.add
grand_child = child.add
root.descendants # => #<Set: {child, grand_child}>
Node
includes the Enumerable
module so you can iterate over a node and its descendants using
any of Enumerable
's methods.
root = UnsortedTree::Node.new
child = root.add
grand_child = child.add
# This will collect all object_ids of a tree.
root.map do |descendant|
descendant.object_id
end
root = UnsortedTree::Node.new
child = root.add
root.root? # => true
child.leaf? # => false
node.root? # => false
child.leaf? # => true
root = UnsortedTree::Node.new
child_1 = root.add
child_2 = root.add
grand_child = child_1.add
root.leaves # => #<Set: {child_2, grand_child}>
child_1.leaves # => #<Set: {grand_child}>
child_2.leaves # => #<Set: {}>
root = UnsortedTree::Node.new
child = root.add
grand_child = child.add
root.depth # => 0
child.depth # => 1
grand_child.depth # => 2
Using node.print
will print a (sub)tree to the console. Example:
#<UnsortedTree::Node:0x00000002caa3d0>
#<UnsortedTree::Node:0x00000002bb7900>
#<UnsortedTree::Node:0x000000027e5200>
#<UnsortedTree::Node:0x000000027343b0>
You can also change the output of this simple print by providing a block:
node.print do |node|
node.object_id
end
will produce:
23417320
22920320
20916480
20554200
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request