0

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?

4
  • The error message is pretty self explanatory: you have a nil and you are trying to do stuff with it. Commented Nov 18, 2012 at 5:15
  • @PicklishDoorknob Sure. I wanted to figure out where generated a nil. I found player is not a nil Commented Nov 18, 2012 at 5:19
  • @PicklishDoorknob .rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/ostruct.rb:174:in method_missing': undefined method []' for nil:NilClass (NoMethodError) from test.rb:6:in `<main>' (referring to the line 'puts player.turn_num') Commented Nov 18, 2012 at 5:27
  • @PicklishDoorknob Edited my question a little bit Commented Nov 18, 2012 at 5:47

1 Answer 1

1

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:

class Player < Node
  def initialize(parent,&block)
    super(parent, :player, &block)
    self.turn_num = 1
  end
end

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 as self.new, you're just returning a bare Node instance, not a Player instance.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.