Ruby on rails 。每个未在数组元素上正确迭代
我有两个ruby类用于在游戏中存储一些自定义日志。Ruby on rails 。每个未在数组元素上正确迭代,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有两个ruby类用于在游戏中存储一些自定义日志。 RoundLog包含与单轮相关的信息,BattleLog只是一个包含多个RoundLog元素的数组 class RoundLog attr_writer :actions, :number def initialize(number) @number = number @actions = [] end def to_a [@number, @actions] end ... end clas
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"]>]
它返回整个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"]>,...]
[#,
#,...]
但是,如果我尝试这样的方法:报告。首先,它正确返回[1,[“老鼠击中测试并造成1点伤害”,“测试击中老鼠并造成1点伤害”]
知道我的代码有什么问题吗?
我尝试将重命名为a
其他名称,因此我认为问题不在于函数名。这是我关于so的第一个问题,请原谅。使用map
而不是每个都可以解决您的问题
each
在块内运行一些操作,然后返回调用了each
的对象/数组/哈希/可枚举/任何对象。map
返回一个新数组,返回值在块中计算。使用map
而不是each
可以解决您的问题
each
在块内运行一些操作,然后返回调用每个的对象/数组/散列/可枚举/任何对象。map
但是返回一个新数组,其中包含在块中计算的返回值。谢谢,它正在工作:)我真的错过了每个dmap
(我以为问题出在其他地方)。谢谢,它起作用了:)我真的错过了和map
之间的重要区别(我以为问题出在其他地方)。
[#<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"]>,...]