无法为对象分配值

时间:2017-11-04 07:53:26

标签: ruby

class Hero
attr_reader :hp
def initialize(name, level, job, hp, strength)
    @name = name
    @level = level.to_i
    @job = job
    @hp = hp.to_i
    @strength = strength.to_i
end

def get_name
    @name
end

def profile
    puts "#{@name} level is #{@level} and hp: #{@hp}"
end

def attack(target) 
    #this line
    target.hp -= @strength
end

def get_hp
    @hp
end
end

#name, level, class/job, hp, strength
yamato = Hero.new("Kross", 16, "Knight", 10, 10)
ciguapal = Hero.new("Ciguapal", 20, "Ghost", 15, 10)


puts yamato.attack(ciguapal)

当我运行脚本时,这就是我得到的:

&#39; calc.rb:20:在attack&#39;:未定义的方法hp=' for #<Hero:0x2eac850> (NoMethodError) Did you mean? hp from calc.rb:33:in&#39;

我试图通过第一个对象降低第二个对象的hp。做一次&#34;攻击&#34;。但我不明白为什么我会一直收到这个错误。

但是,如果我只打印target.hp它确实有用。

谢谢!

1 个答案:

答案 0 :(得分:0)

attr_reader :hp只为@hp生成一个getter方法。但是在attack方法中,您调用了hp,因为

target.hp -= @strength

相同
target.hp = target.hp - @strength

只需更改

attr_reader :hp

attr_accessor :hp

解决此问题。