我定义了一个节点类和播放器类如下:
class Node < OpenStruct
def initialize(parent,tag,&block)
super()
self.parent = parent
self.parent.children << self unless parent.nil?
self.children = []
self.tag = tag
instance_eval(&block) unless block.nil?
end
end
class Player < Node
def initialize(parent)
Node.new(parent,:player) do
self.turn_num = 1
end
end
end
实例变量 player 由
player = Player.new(room) # room is the parent node which was defined
puts player.turn_num
我得到了错误:
in `method_missing': undefined method `[]' for nil:NilClass (NoMethodError)
你能帮我弄清楚哪里出了问题吗?谢谢!
编辑:
问题应该是 Player 类中的初始化。我改变了我的代码
class Player < Node
def self.new(parent)
Node.new(parent,:player) do
self.turn_num = 1
end
end
end
那么就没有报错了。这里的初始化有什么问题呢?