2014-12-25 92 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