Class: Graph

Inherits:
Object
  • Object
show all
Defined in:
lib/graph.rb,
lib/graph/version.rb

Defined Under Namespace

Classes: Edge, Vertex

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vertices = [], edges = []) ⇒ Graph

Returns a new instance of Graph.



8
9
10
11
# File 'lib/graph.rb', line 8

def initialize(vertices = [], edges = [])
  @vertices = vertices
  @edges = edges
end

Instance Attribute Details

#edgesObject (readonly)

Returns the value of attribute edges.



6
7
8
# File 'lib/graph.rb', line 6

def edges
  @edges
end

#verticesObject (readonly)

Returns the value of attribute vertices.



6
7
8
# File 'lib/graph.rb', line 6

def vertices
  @vertices
end

Instance Method Details

#add(vertex_or_edge) ⇒ Object



18
19
20
21
# File 'lib/graph.rb', line 18

def add(vertex_or_edge)
  return add_vertex(vertex_or_edge) if vertex_or_edge.is_a?(Graph::Vertex)
  return add_edge(vertex_or_edge) if vertex_or_edge.is_a?(Graph::Edge)
end

#delete(vertex_or_edge) ⇒ Object



23
24
25
26
# File 'lib/graph.rb', line 23

def delete(vertex_or_edge)
  return delete_vertex(vertex_or_edge) if vertex_or_edge.is_a?(Graph::Vertex)
  return delete_edge(vertex_or_edge) if vertex_or_edge.is_a?(Graph::Edge)
end

#include?(vertex_or_edge) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
# File 'lib/graph.rb', line 13

def include?(vertex_or_edge)
  return include_vertex?(vertex_or_edge) if vertex_or_edge.is_a?(Graph::Vertex)
  return include_edge?(vertex_or_edge) if vertex_or_edge.is_a?(Graph::Edge)
end

#to_hObject



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/graph.rb', line 28

def to_h
  result = {
    vertices: [],
    edges: []
  }
  @vertices.each do |vertex|
    result[:vertices] << vertex.uid
  end
  @edges.each do |edge|
    result[:edges] << { from: edge.from.uid, to: edge.to.uid }
  end
  result
end