【发布时间】:2018-11-07 13:50:11
【问题描述】:
我正在为“连接四”创建一个Grid 类:我从Square 对象创建字符串数组,然后通过在字符串数组上调用transpose 方法创建列数组:
class Grid
Square = Struct.new(:state)
def initialize
@grid_strings = Array.new(6) { Array.new(7) {Square.new} }
@grid_columns = @grid_strings.transpose
end
我有一个方法可以通过更改正确的Square 实例的state 属性将符号放在所选列的末尾:
def put_to_column(column_index, symbol)
column = @grid_columns[column_index - 1]
loop do
square = column.pop
raise "Full column" if square.nil?
if square.state.nil?
square.state = symbol
break
end
end
end
问题是:当我多次调用put_to_column 时,它会正确更改square 对象,但仅在@grid_strings 数组中。如果我检查@grid_columns 数组,所有square 对象仍将state 属性分配给nil。
找不到出错的地方,希望大家帮忙。
【问题讨论】: