I may be making a major design error, but this is my first time working with Structs in Ruby.
As detailed in this question, I have three objects, Vertex, Edge, and Graph. Vertex has simple attributes (scalars), but Edge can have :endpoints
which is a pair of Vertexes in an Array. Specifically, Edge has a scalar :weight
and a Array of Vertexes :endpoints
. Lastly, Graph stores :vertexes
and :edges
, which are Arrays of Vertexes and Edges.
Edge = Struct.new(:weight, :endpoints)
Since Graph is a Struct containing Structs, I created a method to get the scalar weights
from the Graph:
Graph = Struct.new(:vertexes, :edges) do
def get_weights()
w = []
self.edges.each do |ed| w << ed.weight end
end
#truncated
end
However, if I run this, I get Edges, not scalar Integers:
[226] pry(main)> t_weights = [4,8,8,11,7,4,2,9,14,10,2,1,6,7]
=> [4, 8, 8, 11, 7, 4, 2, 9, 14, 10, 2, 1, 6, 7]
[227] pry(main)> t_edges.each_with_index.map do |ed,ind|
[227] pry(main)* ed.weight = t_weights[ind]
[227] pry(main)* ed.endpoints = endpoints[ind]
[227] pry(main)* # p ed.weight
[227] pry(main)* end
t_grap = Graph.new(t_verts, t_edges)
=> #<struct Graph
vertexes=
[#<struct Vertex parent=nil, rank=nil, id=0.31572617312378737>,
#<struct Vertex parent=nil, rank=nil, id=0.24063512558288636>,
#<struct Vertex parent=nil, rank=nil, id=0.34820800389791284>,
#<struct Vertex parent=nil, rank=nil, id=0.86247407897408>,
#<struct Vertex parent=nil, rank=nil, id=0.4503814825928186>,
#<struct Vertex parent=nil, rank=nil, id=0.4020451841058619>,
#<struct Vertex parent=nil, rank=nil, id=0.09096934472128582>,
#<struct Vertex parent=nil, rank=nil, id=0.9942198795853134>,
#<struct Vertex parent=nil, rank=nil, id=0.4393226273344629>], <truncated>
edges=
[#<struct Edge
weight=4,
endpoints=
[#<struct Vertex
parent=#<struct Vertex:...>,
rank=0, <truncated>
[230] pry(main)> t_grap.get_weights
=> [#<struct Edge
weight=4,
endpoints=
[#<struct Vertex
parent=#<struct Vertex:...>,
rank=0,
id=0.6540666040368713>,
#<struct Vertex
parent=#<struct Vertex:...>,
rank=0,
id=0.7511069577638254>]>,
#<struct Edge
weight=8,
endpoints=
[#<struct Vertex
parent=#<struct Vertex:...>,
rank=0,
id=0.6540666040368713>,<truncated>
I tried adding attr_accessor :weights
to Edge, but then the code snippet above which sets the initial values fails silently, leaving each Edge.weight
equal to nil
.
What am I doing wrong?