【发布时间】:2020-03-23 06:07:34
【问题描述】:
问题
我有一个名为 queue 的方法,属于 Board 类,它返回一个空数组。我无法将修改后的对象推送到此数组。目前它返回一个空数组。
def queue
queue = []
end
功能说明
我有一个rules 方法,它属于有条件地调用queue_for_birth 或queue_for_death 的Board 类
def rules(cell)
if something
cell.queue_for_birth
else something_else
cell.queue_for_death
end
end
此方法在包含在game_logic 方法中的每个块中被多次调用,该方法也属于Board 类。
每次调用 rules 时,它应该将 queues_for_birth 或 queues_for_death 添加到一个名为 queue 的数组中。
def game_logic(cells)
cells.each_with_index do |cell,index|
if index == 0
rules(cell) #push to the queue
end
if index == 1
rules(cell) #push to the queue
end
...
这里是添加单元到队列的逻辑所在,它属于Cell类,继承自Board
def queue_for_birth(queue)
@will_survive = true
queue << self
end
但是,每当我调用 board.queue 时,都会返回一个空数组。
=> []
【问题讨论】:
-
为什么你的队列函数没有返回[]?为什么队列 = []?
-
这是一个很好的观察。没有特别的原因。
-
也许你可以看看如何用 ruby 做一个记忆。
-
“我有一个方法 [...],它返回一个空数组。我无法将修改后的对象推送到这个数组” - 这是因为你的方法创建了一个新的每次调用数组。您可能希望返回相同的数组实例。
-
"[...]
Cell类,继承自Board" - 这听起来很奇怪。细胞实际上是一种特殊的板吗?一个单元知道队列是否有意义?
标签: arrays ruby queue each block