Ruby attr_accessor没有被读取

时间:2011-12-21 13:38:17

标签: ruby chipmunk attr-accessor

我正在使用GosuChipmunk宝石开发Ruby游戏。我在名为HeroBullets.rb的文件中有以下类:

require 'gosu'

class HeroBullets
  attr_accessor :y
  def initialize(window)
    @x = 20
    @y = 0
  end
end

我知道需要从另一个文件Physics.rb访问此类,该文件处理所有Chipmunk代码。

在顶部,我有:

require 'chipmunk'

load 'HeroBullets.rb'

class Physics
   attr_accessor :play_area 

def initialize(window)

    @hBullets = Array.new(25)
    @hBullets << HeroBullets.new(window)
    @hBullets << HeroBullets.new(window)
end

进一步说:

  def fire_arrow(y)
    for i in 0...@hBullets.count
      @bullet = @hBullets[i]
      if(@bullet.y == y)
        @hBullets[i].active = true
      end
    end
  end

我得到的错误是:

Physics.rb:112:in block in fire_arrow': undefined methody' for nil:NilClass 
(NoMethodError) from Physics.rb:110:in each' from Physics.rb:110:infire_arrow'
from FileManager.rb:90:in fireHero' from .../lib/main.rb:90:inupdate' from .../lib/main.rb:129:in `'

1 个答案:

答案 0 :(得分:3)

问题是如果@hBullets有10个元素,@hBullets.count将输出10,但@hBullets[10]不起作用,因为数组的索引从{{{}开始1}}不在0。第十个元素将在1中。您收到错误消息,因为您尝试访问的元素是@hBullets[9],而不是因为“attr_accessor未被读取”。

话虽如此,Ruby提供了更简单的方法来迭代数组。我会像这样重写你的代码:

nil

您的代码的另一个问题是您初始化一个新的数组:

def fire_arrow(y)
  @hBullets.each do |bullet|
    bullet.active = true if bullet.y == y
  end
end

这会创建一个包含25个元素的数组,这些元素都是@hBullets = Array.new(25) 。你应该从一个空数组开始:

nil

或者:

@hBullets = Array.new