Getting NameError with code using attr_accessor

165 views Asked by At

This is code to generate moves by each pawn in the game of chess from a particular position.

class Characters
    def initialize(behaviours)
        @position=behaviours.fetch(:assigning_position)
        @right=behaviours.fetch(:moving_right)

    end
    def perform_position
        @position.kmoves
    end
    def perform_right
        @right.rightmove
    end
  end

this is the method for assigning position for a particular pawn.

class Position
    def kmoves
        print "enter x value"
        xpos=STDIN.gets.chomp
        print "enter y value"
        ypos=STDIN.gets.chomp
        print "#{xpos}, #{ypos}\n"
    end
end

this is the method to move pawn by one position to its right

class Right_move < Position
    def rightmove
        puts "compute right moves"
        xpos+=1
    end
end

king = Characters.new( assigning_position:Position.new,moving_right:Right_move.new)
king.perform_position
king.perform_right

I get the error:

in kmoves': undefined local variable or methodxpos' for # (NameError)

1

There are 1 answers

2
williamcodes On

It looks like you've included your attr_accessors in the Characters class instead of the Position class. There's also a typo in your placement of the colon. Try this:

class Position
    attr_accessor :xpos, :ypos

    def kmoves
        print "enter x value"
        xpos = STDIN.gets.chomp
        print "enter y value"
        ypos = STDIN.gets.chomp
        print "#{xpos}, #{ypos}\n"
    end
end

Also, you might want to rename your Characters class to Character because it appears to represent an individual character rather than a collection of them.