Class: Hierarchy::Node
- Inherits:
-
Object
- Object
- Hierarchy::Node
- Defined in:
- lib/hierarchy/node.rb
Overview
A node in a tree structure. A node can have zero or more #children, and has a reverse link back to its parent.
Instance Attribute Summary collapse
-
#children ⇒ Array<Node>
readonly
This node’s children.
-
#content ⇒ Object
The object this node contains.
-
#parent ⇒ Node?
readonly
This node’s parent, or @nil@ if it is a root node.
Instance Method Summary collapse
-
#<<(child) ⇒ Object
Adds a node as a child of this one.
-
#initialize(content) ⇒ Node
constructor
Creates a new root node with no children.
- #inspect ⇒ Object
-
#traverse {|node| ... } ⇒ Object
Performs a depth-first traversal using this as the root node of the tree.
Constructor Details
#initialize(content) ⇒ Node
Creates a new root node with no children.
20 21 22 23 |
# File 'lib/hierarchy/node.rb', line 20 def initialize(content) @children = [] @content = content end |
Instance Attribute Details
#children ⇒ Array<Node> (readonly)
Returns This node’s children.
8 9 10 |
# File 'lib/hierarchy/node.rb', line 8 def children @children end |
#content ⇒ Object
Returns The object this node contains.
14 15 16 |
# File 'lib/hierarchy/node.rb', line 14 def content @content end |
#parent ⇒ Node? (readonly)
Returns This node’s parent, or @nil@ if it is a root node.
11 12 13 |
# File 'lib/hierarchy/node.rb', line 11 def parent @parent end |
Instance Method Details
#<<(child) ⇒ Object
Adds a node as a child of this one. Sets the #parent of the given node.
29 30 31 32 |
# File 'lib/hierarchy/node.rb', line 29 def <<(child) children << child child.instance_variable_set :@parent, self end |
#inspect ⇒ Object
44 45 46 47 48 49 50 51 |
# File 'lib/hierarchy/node.rb', line 44 def inspect str = "#<#{self.class.to_s} #{content.inspect}" unless children.empty? str << ": [ #{children.map(&:inspect).join(', ')} ]" end str << ">" str end |
#traverse {|node| ... } ⇒ Object
Performs a depth-first traversal using this as the root node of the tree.
38 39 40 41 |
# File 'lib/hierarchy/node.rb', line 38 def traverse(&block) children.each { |child| child.traverse &block } block[self] end |