One way to simply populate a list of Vertexes is to use .times
, which seems kind of clumsy, but creates a list (I added an :id
value):
t_verts = []
9.times do t_verts << Vertex.new end
[10] pry(main)> t_verts
=> [#<struct Vertex parent=nil, rank=nil, id=nil>,
#<struct Vertex parent=nil, rank=nil, id=nil>,
#<struct Vertex parent=nil, rank=nil, id=nil>,
#<struct Vertex parent=nil, rank=nil, id=nil>,
#<struct Vertex parent=nil, rank=nil, id=nil>,
#<struct Vertex parent=nil, rank=nil, id=nil>,
#<struct Vertex parent=nil, rank=nil, id=nil>,
#<struct Vertex parent=nil, rank=nil, id=nil>,
#<struct Vertex parent=nil, rank=nil, id=nil>]
This creates different objects.
[11] pry(main)> t_verts.each do |vert|
[11] pry(main)* vert.id = rand
[11] pry(main)* end
=> [#<struct Vertex parent=nil, rank=nil, id=0.755245226082449>,
#<struct Vertex parent=nil, rank=nil, id=0.0167377598961559>,
#<struct Vertex parent=nil, rank=nil, id=0.759799975185007>,
#<struct Vertex parent=nil, rank=nil, id=0.613897002692335>,
#<struct Vertex parent=nil, rank=nil, id=0.0407847317079812>,
#<struct Vertex parent=nil, rank=nil, id=0.549475744759297>,
#<struct Vertex parent=nil, rank=nil, id=0.571876769381891>,
#<struct Vertex parent=nil, rank=nil, id=0.270800829904956>,
#<struct Vertex parent=nil, rank=nil, id=0.814754555208641>]
To add these en masse to a Graph, Simone's method can be used to add the list of Vertexes to the Graph:
def add_vertex(new_verts) # Adds or updates vertexes non-destructively
new_verts.each do |new_vert|
# first case, redundant insert
if self.vertexes.include?(new_vert)
warn "Vertex already exists in graph, no replacement done"
# second case, update
elsif not (update_vert = self.vertexes.select { |vert| vert.id == new_vert.id }).empty?
self.vertexes[self.vertexes.index(update_vert)] = new_vert
# third case, append new
else
self.vertexes ||= []
self.vertexes << vertex
end
end
end
It looks like I need to build a constructor method that builds the Graph from an adjacency list and weight list; I don't see a simple way to do this in one big step.