。不能在数组元素上正确迭代

时间:2014-12-25 21:52:58

标签: 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

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重命名为其他内容,因此我认为问题不在于函数名称。这是我关于SO的第一个问题,所以请放纵。

1 个答案:

答案 0 :(得分:4)

使用map代替each可以解决您的问题。

each在块内运行一些操作,然后返回对象/ array / hash / enumerable /调用each的任何内容。但是,map会返回一个新数组,其中包含在块中计算的返回值。