Ruby:nil:NilClass /继承问题的未定义方法`[]'?

时间:2018-09-25 12:36:56

标签: ruby

能否请您向我解释为什么会出现此错误,我想这是由于我定义实例变量的方式所致:

我有一个名为“字符”的父类

class Character
  attr_accessor :coordinates

  def initialize (coordinates)
    @coordinates = []
  end
end

还有一个子班:

require_relative 'characters'

class Hero < Character
  attr_accessor :lives, :coordinates

  def initialize (lives, coordinates)
    @lives = lives
    @coordinates = []
  end

  def get_direction
    puts "Press up/down and left/right keys to start moving your hero"
    next_move = gets.chomp.downcase
    if next_move == 'left'
      @coordinates = [0, -1]
    elsif next_move == 'right'
      @coordinates = [0, 1]
    elsif next_move == 'up'
      @coordinates = [-1, 0]
      elif next_move == 'down'
      @coordinates = [1, 0]
    end
  end
end

然后我有一个main.rb,我想在其中使用角色的@coordinates并检查他是否仍在地图上。这是main.rb中的方法:

def check_hero_position
    print @coordinates.class
    print @coordinates[0].class

    # @hero_location[1] += @coordinates[1]
    # case  
    # when (@hero_location[0] < 1) || (@hero_location[0] > @map_size[0]) 
    #   puts "error-x"
    # when
    #   (@hero_location[1] < 0) || (@hero_location[1] > @map_size[1])
    #   puts "error-y"
    # end
end

运行代码时,在尝试打印坐标类[0]的方法中,该行出现此错误。 check_hero_position': undefined method []'代表nil:NilClass

我是否正确使用了coordinates实例变量? 第二,如何比较两个数组的值?我注释了该方法中的代码,因为它不正确。

1 个答案:

答案 0 :(得分:1)

首先要在初始化中为@coordinates分配空数组,所以请进行如下更改:

class Hero < Character
  attr_accessor :lives, :coordinates

  def initialize (lives, coordinates = [])
    @lives = lives
    @coordinates = coordinates # assign the value of the parameter
  end

  def get_direction
    puts "Press up/down and left/right keys to start moving your hero"
    next_move = gets.chomp.downcase
    if next_move == 'left'
      @coordinates = [0, -1]
    elsif next_move == 'right'
      @coordinates = [0, 1]
    elsif next_move == 'up'
      @coordinates = [-1, 0]
      elif next_move == 'down'
      @coordinates = [1, 0]
    end
  end
end

然后,您需要实例化Hero对象,并传递参数进行初始化:

hero = Hero.new('something', [:x,:y,:z])

现在您可以在其上调用该方法:

p hero.coordinates #=> [:x, :y, :z]


对于问题的第二部分,我建议您看一下Vector类以进行移动和比较,也许您会发现有用的:

require 'matrix'

position = Vector[1, 2]
move = Vector[4, 6]

new_position = position + move #=> Vector[5, 8]
p new_position.magnitude #=> 9.433981132056603 (distance from origin 0, 0)