Ruby 如何从im使用的函数中引用对象
我正在学习ruby,我正在编写一个简单的文本游戏,在这个游戏中,我们将与对手作战。我有一个“英雄”类,我有这样的代码Ruby 如何从im使用的函数中引用对象,ruby,Ruby,我正在学习ruby,我正在编写一个简单的文本游戏,在这个游戏中,我们将与对手作战。我有一个“英雄”类,我有这样的代码 def attack(enemy) enemy.hp -= attack_damage puts enemy.name + " HP:" + enemy.hp.to_s enemy.attack(# This is the place where I need to refer to object from what I'm calling this
def attack(enemy)
enemy.hp -= attack_damage
puts enemy.name + " HP:" + enemy.hp.to_s
enemy.attack(# This is the place where I need to refer to object from what I'm calling this method #)
end
当我想进行战斗时,我只创建新的英雄和敌人,但我不能使用递归,因为我不知道如何引用对象,正如我所说的,所以战斗只持续1次命中
abundzu = Hero.new("abundzu", 100, 25, 5)
herr = Hero.new("herr", 50, 25, 5)
abundzu.attack(herr)
只需使用
self
:
def attack(enemy)
enemy.hp -= attack_damage
puts "#{enemy.name} HP: #{enemy.hp}"
enemy.attack(self)
end