【问题标题】:Ruby nested for loop to populate array of arraysRuby 嵌套 for 循环以填充数组数组
【发布时间】:2018-03-02 16:23:22
【问题描述】:

我正在尝试通过编写 Conway 的生命游戏来自学 Ruby。

我学习数组如何工作的初步步骤之一是创建一个 Cell 对象数组数组,定义如下:

class Cell
  def initialize(status, xpos, ypos)
    @status = status
    @position = [xpos,ypos]
  end
end

contents = Array.new(10, Array.new(10))

for i in 0..contents.length-1
  for j in 0..9
    contents.at(i).insert(j, Cell.new("DEAD", i, j))
  end
end

我希望<code>contents</code> 是一个大小为 10 的数组(它是),其中每个内部数组的大小也是 10;但是每个内部数组最终的大小都是 110,这是为什么呢?

编辑

看来我的主要问题是误解了插入的工作原理。我已经将我的代码更改为如下:

class Cell
  def initialize(status, xpos, ypos)
    @status = status
    @position = [xpos,ypos]
  end

  def declare_state
    puts "Position is [" + @position[0].to_s + ", " + @position[1].to_s + "] and status is " + @status
  end
end

contents = Array.new(10, Array.new(10))

for i in 0..9
  for j in 0..9
    contents[i][j] = Cell.new("DEAD", i, j))
  end
end

contents.each {
  |subarray| subarray.each {
    |cell| cell.declare_status
  }
}

看起来我的所有 Cell 对象的所有 @xpos 值都设置为 9,这是出乎意料的。

【问题讨论】:

  • 缩进使用两个空格。
  • 为什么不使用更小的数组来简化你的代码,那么为什么会发生这种情况就很明显了。
  • 啊,看来我误解了插入的工作原理。但是,我仍然没有得到我想要的结果,我会更新问题以匹配。

标签: ruby for-loop multidimensional-array


【解决方案1】:

我知道这没有直接关系,但是解决这个问题的一种方法是使用 ruby​​ 更惯用的方法是使用 each_with_index 而不是嵌套 for 循环。它看起来像这样:

class Cell
    def initialize(status, xpos, ypos)
      @status = status
      @position = [xpos,ypos]
    end
end

contents = Array.new(10, Array.new(10))

contents.each_with_index do |row, row_index|
  row.each_with_index do |cell, cell_index|
    contents[row_index][cell_index] = Cell.new("DEAD", row_index, cell_index)
  end
end

【讨论】:

    【解决方案2】:

    行内:

    contents = Array.new(10, Array.new(10))
    

    创建了一个有 10 个位置的数组。您可能没有意识到这些位置中的每一个都填充了相同的数组。

    我想你想要

    contents = Array.new(10) { Array.new(10) }
    

    【讨论】:

    • 刚刚回答了我遇到的问题,谢谢!
    【解决方案3】:

    这里有两个问题。首先是您使用insert,它在子数组中创建新元素而不是编辑值。您可以使用contents[i][j] = cell 而不是contents.at(i).insert(j, cell),其中cell 是您的单元格对象。

    第二个问题是您对contents = Array.new(10, Array.new(10)) 的使用是创建一个包含10 个元素的数组,这些元素引用相同的single 数组引用。如果你对每个子数组运行object_id,你会看到它们都指向同一个对象。结果,更新其中一个子数组似乎会更新所有子数组。

    【讨论】:

      猜你喜欢
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      相关资源
      最近更新 更多