ruby - 将实例变量设置为 'self' ?

标签 ruby class self

我正在用两个类创建 Conway 的生命游戏:Board 和 Cell。

Board 可以访问 Cell,但我不太清楚具体是如何访问的。我不能将 cell.board = self 放在 Cell 的初始化方法下吗?为什么或者为什么不?例如,这是我认为相关的部分。

class Board
  #omitted variables & methods    

    def create_cell
        cell = Cell.new
        cell.board = self
    end
end

class Cell
    attr_accessor :board

    def initialize
    end
end    

此外,cell.board = self 究竟做了什么?

最佳答案

您的代码中有错误。您应该使用 cell = Cell.new 而不是 cell = Class.new。 是的,您可以将电路板(自身)作为参数传递到 Cell 的构造函数(初始化)中。事实上,那样更干净、更实用。查看这段代码:

class Board
  def create_cell
    cell = Cell.new(self)
  end
end

class Cell
  attr_accessor :board

  def initialize board
    @board = board
  end
end

然后是一些使用示例。

$> b = Board.new
 # => #<Board:0x000001021c0298> 
$> c1 = b.create_cell
 # => #<Cell:0x000001021c27a0 @board=#<Board:0x000001021c0298>> 
$> c2 = b.create_cell
 # => #<Cell:0x000001021d4270 @board=#<Board:0x000001021c0298>> 
$> c2.board == c1.board
 # => true

如您所见,cell.board = self 或使用 constructor(初始化)将当前板实例设置到创建的单元格中。所以所有这些单元格都将指向该板。

关于ruby - 将实例变量设置为 'self' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22264062/

相关文章:

ruby-on-rails - 在 Ruby on Rails 中从数据库预加载数据

java - 如何找到方法中调用的所有方法?

class - 为什么 Swift 初始化器不能在它们的父类(super class)上调用便利初始化器?

ruby - 'input = self' 和 'input = self.dup' 有什么区别

python - (Python) 通过单选按钮 python 更新背景

ruby-on-rails - Ruby 字符串重音错误 : More than meet the eyes

ruby - 如何在 Ruby 脚本中为命令 shell 获取环境变量?

swift - 使核心数据类成为最终类以满足协议(protocol) 'Self' 要求

ruby - 如何使用 Chef 延迟评估任意变量

php - 有什么方法可以在 PHP 中安全地重新声明一个类?