Ruby 使用attr\u访问器获取代码的NameError

Ruby 使用attr\u访问器获取代码的NameError,ruby,inheritance,attr-accessor,Ruby,Inheritance,Attr Accessor,这是国际象棋游戏中每个棋子从特定位置生成移动的代码 class Characters def initialize(behaviours) @position=behaviours.fetch(:assigning_position) @right=behaviours.fetch(:moving_right) end def perform_position @position.kmoves end de

这是国际象棋游戏中每个棋子从特定位置生成移动的代码

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
这是指定特定棋子位置的方法

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
这是将兵向右移动一个位置的方法

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
类右移动
我得到一个错误:

kmoves中:未定义的局部变量或方法#(NameError)


看起来您将属性访问器包含在
字符
类中,而不是
位置
类中。你的冒号位置也有错误。试试这个:

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

此外,您可能希望将
Characters
类重命名为
Character
,因为它似乎表示单个字符,而不是它们的集合。

我实际上正在尝试创建一个常用的移动方法,例如右键,左对角线等和il实现了一个rake文件,在该文件中,我将根据pawns调用for循环中的每个方法。in
rightmove:undefined method
+”for nil:NilClass(NoMethodError