Ruby attr_accessor 未被读取
我正在使用 Gosu
和 Chipmunk
gems 使用 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 [email protected]
@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 `'
I am developing a game with Ruby using the Gosu
and Chipmunk
gems. I have the following class in the file named HeroBullets.rb
:
require 'gosu'
class HeroBullets
attr_accessor :y
def initialize(window)
@x = 20
@y = 0
end
end
I know need to access this class from another file, Physics.rb
which handles all the Chipmunk
code.
At the top I have:
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
And further down there is:
def fire_arrow(y)
for i in [email protected]
@bullet = @hBullets[i]
if(@bullet.y == y)
@hBullets[i].active = true
end
end
end
The Error I get is:
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 `'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,如果
@hBullets
有 10 个元素,@hBullets.count
将输出10
,但@hBullets[10]< /code> 不起作用,因为数组的索引从
0
开始,而不是从1
开始。第十个元素将位于@hBullets[9]
中。您收到错误消息是因为您尝试访问的元素为 nil,而不是因为“attr_accessor 未被读取”。话虽如此,Ruby 提供了更简单的方法来迭代数组。我会这样重写您的代码:
您的代码的另一个问题是您像这样初始化一个新数组:
这将创建一个包含 25 个元素的数组,这些元素全部为 nil。您应该从一个空数组开始:
或者:
The problem is that if
@hBullets
has 10 elements,@hBullets.count
will output10
, but@hBullets[10]
does not work, because the index of an array starts at0
not at1
. The tenth element will be in@hBullets[9]
. You get the error message because the element you are trying to access isnil
, not because "attr_accessor is not being read".That being said, Ruby offers much easier ways to iterate over an array. I would rewrite your code like this:
Another problem with your code is that you initialize a new array like this:
This creates an array with 25 elements that are all
nil
. You should start with an empty array instead:Or: