I defined a node class and player class as following:
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
The instance variable player was created by
player = Player.new(room) # room is the parent node which was defined
puts player.turn_num
And I got the error:
in `method_missing': undefined method `[]' for nil:NilClass (NoMethodError)
Could you help me figure out where went wrong? Thanks!
Edit:
The problem should be the initialize in the Player class. I changed my codes
class Player < Node
def self.new(parent)
Node.new(parent,:player) do
self.turn_num = 1
end
end
end
Then there is no error.What’s wrong with the initialize here?
You don’t need to initialize a Node inside Player, because any Player instance is already also a Node instance. Instead, you should pass the expected arguments into
super:Generally, it’s a bad idea to override
.new– this is defined by default for all Ruby objects to allocate memory and then run the initialize method (if it exists). When you override it asself.new, you’re just returning a bareNodeinstance, not aPlayerinstance.