访问Struct中包含的Struct的属性

时间:2013-12-14 11:15:20

标签: ruby struct

我可能会犯一个重大的设计错误,但这是我第一次使用Ruby中的Structs。

As detailed in this question,我有三个对象,Vertex,Edge和Graph。 Vertex具有简单属性(标量),但Edge可以具有:endpoints,它是数组中的一对顶点。具体来说,Edge有一个标量:weight和一个顶点数组:endpoints。最后,图表存储:vertexes:edges,它们是顶点和边缘的数组。

Edge = Struct.new(:weight, :endpoints)

由于Graph是包含Structs的Struct,我创建了一个从图中获取标量weights的方法:

Graph = Struct.new(:vertexes, :edges) do
  def get_weights()
    w = []
    self.edges.each do |ed| w << ed.weight end
  end

#truncated
end

但是,如果我运行它,我得到Edges,而不是标量整数:

[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>

我尝试将attr_accessor :weights添加到Edge,但之后设置初始值的代码段无声地失败,使每个Edge.weight等于nil

我做错了什么?

1 个答案:

答案 0 :(得分:1)

不确定为什么在调用Graph.new

时需要顶点

边缘应该已经在端点中包含它们。

Vertex = Struct.new(:x, :y)
Edge = Struct.new(:weight, :endpoints)

Graph = Struct.new(:edges) do
  def get_weights
    edges.map(&:weight)
  end
end

e1 = Edge.new 66, [Vertex.new(1,2), Vertex.new(2,1)]
e2 = Edge.new 26, [Vertex.new(1,1), Vertex.new(2,1)]
g = Graph.new([e1,e2])
g.get_weights
=> [66, 26] 

编辑:

g.edges.each { |edge| p edge.weight }
66
26
...

的工作原理。你可能正在构建不同的东西。上面的代码创建了一个Graph对象,其中包含一个名为edges的Edge对象数组。

ed_ary.map[&:weight]

不起作用。正如在我的评论中g.edges.map(&:weight)只是一个捷径。请参阅此讨论:What does to_proc method mean?