You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中调用hit_zom?方法遇NilClass未定义方法错误求助

未定义方法错误:undefined method hit_zom?' for nil:NilClass`

错误具体信息如下:

`update': undefined method `hit_zom?' for nil:NilClass (NoMethodError)

        if @zombie.hit_zom?(bullet)\r
                  ^^^^^^^^^

我已在Zombie类中定义hit_zom?方法:

def hit_zom?(bullet)
  bullet.box && [[bullet.box.x1, bullet.box.y1], [bullet.box.x2, bullet.box.y2],
  [bullet.box.x3, bullet.box.y3], [bullet.box.x4, bullet.box.y4]].any? do |coordinates|
    @box.contains?(coordinates[0], coordinates[1])
  end
end

并在update方法中调用该方法:

if @zombie.hit_zom?(bullet)
  puts "sang noob"
end

但仍触发上述错误,排查许久未找到解决方案,希望能得到帮助。


问题解决更新

感谢评论区Stefan先生的建议,我已修复该错误,现将解决方案分享给大家:

完整的update方法代码如下:

def update
       
  if Window.frames % 360 == 0
    @zombie = Zombie.new
    @horde << @zombie 
    @zombie.reanimate
    if @zombie.hit_zom?(bullet)
      puts "sang noob"
    end
  end
  @horde.each { |zombie| zombie.move }
end

问题原因

hit_zom?的判断条件原本位于Window.frame的条件分支之外,导致@zombie未被初始化时就被调用,此时@zombie为nil,进而触发了NoMethodError。

内容的提问来源于stack exchange,提问作者Kar98k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:55:44