首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >nil:NilClass (NoMethodError)的未定义方法‘-’

nil:NilClass (NoMethodError)的未定义方法‘-’
EN

Stack Overflow用户
提问于 2017-05-04 17:19:40
回答 2查看 4.2K关注 0票数 2

我不知道如何修复它,所以它从health类变量中去掉了10个,因为它说这是一个错误。

代码语言:javascript
复制
/home/will/Code/Rubygame/objects.rb:61:in `attacked': undefined method `-' for nil:NilClass (NoMethodError)
    from ./main.rb:140:in `update'
    from /var/lib/gems/2.3.0/gems/gosu-0.10.8/lib/gosu/patches.rb:140:in `tick'
    from /var/lib/gems/2.3.0/gems/gosu-0.10.8/lib/gosu/patches.rb:140:in `tick'
    from ./main.rb:197:in `<main>'

以下是main中的代码:

代码语言:javascript
复制
def update
    @player.left if Gosu::button_down? Gosu::KbA
    @player.right if Gosu::button_down? Gosu::KbD
    @player.up if Gosu::button_down? Gosu::KbW
    @player.down if Gosu::button_down? Gosu::KbS
    if Gosu::button_down? Gosu::KbK 
        @player.shot if @player_type == "Archer" or @player_type == "Mage"
        if @object.collision(@xshot, @yshot) == true
            x, y, health = YAML.load_file("Storage/info.yml")
            @object.attacked #LINE 140
        end
    end

end

这就是@object.attacked指向的地方:

代码语言:javascript
复制
 def attacked
    puts "attacked"
    @health -= 10 #LINE 61
    @xy.insert(@health)
    File.open("Storage/info.yml", "w") {|f| f.write(@xy.to_yaml) }
    @xy.delete_at(2)
    if @health == 0
        @dead = true
    end
end 

和yaml文件(如果需要):

代码语言:javascript
复制
   ---
   - 219.0
   - 45.0
   - 100.0

我试着把健康放在@ .to_i后面,就像这样:

代码语言:javascript
复制
   @health.to_i -= 10

但它只会带来另一个错误:

代码语言:javascript
复制
   undefined method `to_i=' for nil:NilClass (NoMethodError)
EN

回答 2

Stack Overflow用户

发布于 2017-05-04 17:27:32

错误消息告诉您attacked方法中的@health == nil。你需要在某个地方初始化这个值!通常,这将位于类的适当命名的initialize方法中。或者,继续您到目前为止提供的代码,如果当有人第一次受到攻击时,您想要将@health实例变量设置为默认值,您可以将其更改为:

代码语言:javascript
复制
def attacked
  @health ||= 100 # or whatever
  puts "attacked"
  @health -= 10 #LINE 61
  @xy.insert(@health)
  File.open("Storage/info.yml", "w") {|f| f.write(@xy.to_yaml) }
  @xy.delete_at(2)
  if @health == 0
    @dead = true
  end
end 

注意:健康语法是ruby的条件赋值运算符-它意味着‘将@health设置为100,除非已经定义了@ ||=

票数 2
EN

Stack Overflow用户

发布于 2017-05-04 20:02:39

正如@omnikron所提到的,您的@health未初始化,因此-=在尝试从nil中减去时会抛出异常。如果我们使用initialize方法,我想象你的对象类如下:

代码语言:javascript
复制
Class Object
  attr_accessor :health

  def initialize
    @health = 100
  end
end

def attacked
  puts "attacked"
  @object.health -= 10 #LINE 61
  @xy.insert(@object.health)
  File.open("Storage/info.yml", "w") {|f| f.write(@xy.to_yaml) }
  @xy.delete_at(2)
  if @health == 0
    @dead = true
  end
end
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43778796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档