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
重命名为其他内容,所以我不认为问题出现在函数名称中。这是我的第一个问题,所以请放纵。
谢谢,它的工作:)我真的错过了'each'和'map'之间的重要区别(我认为问题在别的地方)。 – switowski