【问题标题】:Pushing objects into an array is returning an empty array将对象推入数组将返回一个空数组
【发布时间】:2020-03-23 06:07:34
【问题描述】:

问题

我有一个名为 queue 的方法,属于 Board 类,它返回一个空数组。我无法将修改后的对象推送到此数组。目前它返回一个空数组。

def queue
  queue = []
end

功能说明

我有一个rules 方法,它属于有条件地调用queue_for_birthqueue_for_deathBoard

def rules(cell)
    if something
      cell.queue_for_birth
    else something_else
      cell.queue_for_death
    end
  end

此方法在包含在game_logic 方法中的每个块中被多次调用,该方法也属于Board 类。 每次调用 rules 时,它应该将 queues_for_birthqueues_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 时,都会返回一个空数组。 =&gt; []

【问题讨论】:

  • 为什么你的队列函数没有返回[]?为什么队列 = []?
  • 这是一个很好的观察。没有特别的原因。
  • 也许你可以看看如何用 ruby​​ 做一个记忆。
  • “我有一个方法 [...],它返回一个空数组。我无法将修改后的对象推送到这个数组” - 这是因为你的方法创建了一个新的每次调用数组。您可能希望返回相同的数组实例。
  • "[...] Cell 类,继承自 Board" - 这听起来很奇怪。细胞实际上是一种特殊的板吗?一个单元知道队列是否有意义?

标签: arrays ruby queue each block


【解决方案1】:

将实例变量queue 添加到板类解决了这个问题

class Board
  def initialize(live_cell_count, queue)
    @live_cell_count = live_cell_count
    @queue = queue
  end

  def queue
    @queue
  end

在条件中插入queue.push(cell) 成功地将每个单元格附加到queue 数组中。

def rules(cell)
    if something
      cell.queue_for_birth
      @queue.push(cell)
    else something_else
      cell.queue_for_death
      @queue.push(cell)
    end
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 2017-05-01
    • 2017-10-10
    • 2023-03-14
    • 1970-01-01
    • 2017-12-05
    相关资源
    最近更新 更多