Class: Node
Overview
Represents to a node in the graph
Author: Johnny Lee Othon
Instance Attribute Summary collapse
-
#id ⇒ Object
Returns the value of attribute id.
-
#name ⇒ Object
Returns the value of attribute name.
Instance Method Summary collapse
- #<=>(other) ⇒ Object
- #add_edge(node, cost) ⇒ Object
- #cost(node) ⇒ Object
-
#edges ⇒ Object
Gets an enumerator of the edges.
-
#initialize(id, name = nil) ⇒ Node
constructor
A new instance of Node.
-
#inspect ⇒ Object
Returns the name of the node or its id as a string.
-
#key ⇒ Object
Gets the name if exists or the id.
-
#to_adjacency_list ⇒ Object
Returns the node in the format
<id:name>. -
#to_s ⇒ Object
Returns the name of the node or its id as a string.
Constructor Details
#initialize(id, name = nil) ⇒ Node
Returns a new instance of Node.
10 11 12 13 14 |
# File 'lib/usearchtree/node.rb', line 10 def initialize id, name=nil @name = name @id = id @edges = Array.new end |
Instance Attribute Details
#id ⇒ Object
Returns the value of attribute id.
6 7 8 |
# File 'lib/usearchtree/node.rb', line 6 def id @id end |
#name ⇒ Object
Returns the value of attribute name.
6 7 8 |
# File 'lib/usearchtree/node.rb', line 6 def name @name end |
Instance Method Details
#<=>(other) ⇒ Object
26 27 28 |
# File 'lib/usearchtree/node.rb', line 26 def <=> other return @id <=> other.id end |
#add_edge(node, cost) ⇒ Object
45 46 47 |
# File 'lib/usearchtree/node.rb', line 45 def add_edge node, cost @edges << Edge.new(node, cost) end |
#cost(node) ⇒ Object
49 50 51 52 53 54 |
# File 'lib/usearchtree/node.rb', line 49 def cost node edge = @edges.find{|e| e.node == node} if edge edge.cost end end |
#edges ⇒ Object
Gets an enumerator of the edges
62 63 64 |
# File 'lib/usearchtree/node.rb', line 62 def edges return @edges.each end |
#inspect ⇒ Object
Returns the name of the node or its id as a string.
22 23 24 |
# File 'lib/usearchtree/node.rb', line 22 def inspect self.to_s end |
#key ⇒ Object
Gets the name if exists or the id
57 58 59 |
# File 'lib/usearchtree/node.rb', line 57 def key @name or @id end |
#to_adjacency_list ⇒ Object
Returns the node in the format <id:name>.
31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/usearchtree/node.rb', line 31 def to_adjacency_list s = "#{name}" unless @name.nil? or @name.empty? s += "(#{@id})" end unless @edges.empty? s += ": " end nodes = @edges.map do |edge| "#{edge.node}=>#{edge.cost}" end.join(", ") s += nodes end |
#to_s ⇒ Object
Returns the name of the node or its id as a string.
17 18 19 |
# File 'lib/usearchtree/node.rb', line 17 def to_s @name or "#{@id}" end |