2014-12-25 132 views
1

我有兩個ruby類用於在遊戲中存儲一些自定義日誌。 RoundLog包含與單輪相關的信息,而BattleLog只是包含多個RoundLog元素的數組。。每個元素都不能正確迭代數組元素

class RoundLog 
    attr_writer :actions, :number 

    def initialize(number) 
    @number = number 
    @actions = [] 
    end 
    def to_a 
    [@number, @actions] 
    end 
    ... 
end 

class BattleLog 
    attr_accessor :rounds 
    def initialize 
    @rounds = [] 
    end 
    def print 
    @rounds.each do |round| 
     round.to_a 
    end 
    end 
    ... 
end 

如果我有以下BattleLog實例:

report = [#<RoundLog:0x00000008ab8328 @number=1, @actions=["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"]>, 
#<RoundLog:0x00000008acc170 @number=2, @actions=["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"]>, 
#<RoundLog:0x00000008aef5f8 @number=3, @actions=["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"]>, 
#<RoundLog:0x00000008b02978 @number=4, @actions=["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"]>, 
#<RoundLog:0x00000008b1a280 @number=5, @actions=["Rat hits Test and deals 1 points of damage"]>] 

然後將下面這段代碼是不工作:report.each {|x| x.to_a} 而是像返回格式正確的信息:

[1, ["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"], 
[2, ["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"], ...] 

它返回整個RoundLog對象:

[#<RoundLog:0x00000008ab8328 @number=1, @actions=["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"]>, 
#<RoundLog:0x00000008acc170 @number=2, @actions=["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"]>,...] 

但是,如果我嘗試這樣的:report.first.to_a它正確返回[1, ["Rat hits Test and deals 1 points of damage", "Test hits Rat and deals 1 points of damage"] 任何想法我的代碼有什麼問題嗎? 我嘗試將to_a重命名爲其他內容,所以我不認爲問題出現在函數名稱中。這是我的第一個問題,所以請放縱。

回答

4

使用map而不是each應該可以解決您的問題。

each在塊內部運行一些操作,然後返回對象/ array/hash/enumerable /無論each被調用。然而,map會返回一個新數組,其中返回的值是在您的塊中計算的。

+0

謝謝,它的工作:)我真的錯過了'each'和'map'之間的重要區別(我認爲問題在別的地方)。 – switowski