Class: RubyAi::Search::Graph

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_ai/search/graph.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(directed:, &block) ⇒ Graph

Returns a new instance of Graph.



21
22
23
24
25
26
# File 'lib/ruby_ai/search/graph.rb', line 21

def initialize(directed:, &block)
  @vertices = []
  @edges    = []
  @directed = directed
  instance_eval(&block) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, **kwargs, &block) ⇒ Object



28
29
30
# File 'lib/ruby_ai/search/graph.rb', line 28

def method_missing(method, *args, **kwargs, &block)
  send(method, *args, **kwargs, &block)
end

Instance Attribute Details

#edgesObject (readonly)

Returns the value of attribute edges.



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

def edges
  @edges
end

#verticesObject (readonly)

Returns the value of attribute vertices.



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

def vertices
  @vertices
end

Class Method Details

.directed(&block) ⇒ Object



12
13
14
# File 'lib/ruby_ai/search/graph.rb', line 12

def directed(&block)
  new(directed: true, &block)
end

.undirected(&block) ⇒ Object



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

def undirected(&block)
  new(directed: false, &block)
end

Instance Method Details

#edge(from:, to:, cost: 1) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/ruby_ai/search/graph.rb', line 37

def edge(from:, to:, cost: 1)
  start_vertex = find_or_create_vertex(name: from)
  end_vertex   = find_or_create_vertex(name: to)
  
  create_forward_edge(start_vertex: start_vertex, end_vertex: end_vertex, cost: cost)
  create_reverse_edge(start_vertex: start_vertex, end_vertex: end_vertex, cost: cost) unless @directed
  self
end

#vertex(name) ⇒ Object



32
33
34
35
# File 'lib/ruby_ai/search/graph.rb', line 32

def vertex(name)
  @vertices.push(Vertex.new(name: name))
  self
end