lib/redwood.rb in redwood-0.1.1 vs lib/redwood.rb in redwood-0.1.2

- old
+ new

@@ -2,11 +2,11 @@ # Its primary implementation is the Redwood::Node class. Its only requirement # is that the tree-infused-object's children and parent is an object that # also mixes in tree-like methods. See Redwood::Node for the canononical representation. module Redwood - VERSION = "0.1.1" + VERSION = "0.1.2" # This node's parent. def parent @parent end @@ -80,10 +80,21 @@ # The root node has a depth of 1, its children have a depth of 2, etc. def depth ancestors.size + 1 end + # From Wikipedia: The height of a node is the length + # of the longest downward path to a leaf from that node. + # In other words, the length of this node to its furthest descendant. + def height + if !leaf? + descendants.collect {|child| child.depth }.uniq.size + 1 + else + 1 + end + end + # Orphan this node. Remove it from its parent node. def unlink if parent parent.children.delete(self) self.instance_variable_set(:@parent, nil) @@ -94,9 +105,16 @@ # Abandon all of this node's children. def prune if children children.each {|child| child.unlink } end + end + + # Append a node to this node's children, and return the node. + def graft(node) + node.instance_variable_set(:@parent, self) + children << node + node end # Recursively yield every node in the tree. def walk(&block) if block_given? \ No newline at end of file