【发布时间】: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