Class: Hierarchy::Node

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(content) ⇒ Node

Creates a new root node with no children.

Parameters:

  • content

    The content the node will contain.



20
21
22
23
# File 'lib/hierarchy/node.rb', line 20

def initialize(content)
  @children = []
  @content = content
end

Instance Attribute Details

#childrenArray<Node> (readonly)

Returns This node’s children.

Returns:

  • (Array<Node>)

    This node’s children.



8
9
10
# File 'lib/hierarchy/node.rb', line 8

def children
  @children
end

#contentObject

Returns The object this node contains.

Returns:

  • The object this node contains.



14
15
16
# File 'lib/hierarchy/node.rb', line 14

def content
  @content
end

#parentNode? (readonly)

Returns This node’s parent, or @nil@ if it is a root node.

Returns:

  • (Node, nil)

    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.

Parameters:

  • child (Node)

    The node to add as a child of this node.



29
30
31
32
# File 'lib/hierarchy/node.rb', line 29

def <<(child)
  children << child
  child.instance_variable_set :@parent, self
end

#inspectObject



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.

Yields:

  • (node)

    Each node in depth-first order.

Yield Parameters:

  • node (Node)

    A child node.



38
39
40
41
# File 'lib/hierarchy/node.rb', line 38

def traverse(&block)
  children.each { |child| child.traverse &block }
  block[self]
end