我目前正在做实用的工作室课程,这是我为其中一个练习编写的一些代码。当我运行代码时,除了我打算调用的方法之外,我还获得了一个对象 ID。该练习创建了一个游戏,您可以在其中使用 blam 或 w00t 方法增加或减少玩家的健康状况。
class Player ##creates a player class
attr_accessor :fname, :lname, :health
def initialize fname, lname, health=100
@fname, @lname, @health = fname.capitalize, lname.capitalize, health
end
def to_s
#defines the method to introduce a new player
#replaces the default to_s method
puts "I'm #{@fname} with a health of #{@health}."
end
def blam #the method for a player to get blammed?
@health -= 10
puts "#{@fname} got blammed!"
end
def w00t #the method for a player getting wooted
@health += 15
puts "#{@fname} got w00ted"
end
end
larry = Player.new("larry","fitzgerald",60)
curly = Player.new("curly","lou",125)
moe = Player.new("moe","blow")
shemp = Player.new("shemp","",90)
puts larry
puts larry.blam
puts larry
puts larry.w00t
puts larry
我的输出如下所示:
I'm Larry with a health of 60.
#<Player:0x10e96d6d8>
Larry got blammed!
nil
I'm Larry with a health of 50.
#<Player:0x10e96d6d8>
Larry got w00ted
nil
I'm Larry with a health of 65.
#<Player:0x10e96d6d8>
当我运行代码时,我无法弄清楚为什么对象 ID(或 nil)会打印到控制台。谢谢!