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