2013-12-14 33 views
1

我可能會犯一個主要的設計錯誤,但這是我第一次在Ruby中使用Structs。訪問Struct中包含的Struct的屬性

As detailed in this question,我有三個對象,Vertex,Edge和Graph。頂點具有簡單的屬性(標量),但Edge可以有一個數組中的一對頂點。具體來說,Edge有一個標量:weight和一個頂點陣列:endpoints。最後,Graph存儲:vertexes:edges,它們是頂點和邊的數組。

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

由於圖形是包含的Structs一個結構,我創建了一個方法,從圖中得到標weights

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

#truncated 
end 

但是,如果我跑,我得到邊緣,而不是標量的整數:

[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.weight等於nil

我在做什麼錯?

回答

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對象,其中包含一個稱爲邊的Edge對象數組。

ed_ary.map[&:weight] 

不起作用。正如我在評論g.edges.map(&:weight)只是一個捷徑。看到這個討論:What does to_proc method mean?


+0

絕對有效,但我無法理解amp運算符。如果我只是在圖的外部有一個邊的數組,爲什麼'ed_ary.each do | ed | p ed.weight end'或'ed_ary.map [&:weight]'返回存儲的權重? –

+1

對不起,我應該保持熟悉。它與'edges.map {| edge |相同edge.weight}' – seph