I am currently doing pragmatic studios course and this is some code I wrote for one of the exercises. When I run the code I get an object id in addition to the method I intended to call. The exercise creates a game where you can increase or decrease a players health using a blam or w00t method.
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
My output looks like this:
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>
I can’t figure out why the object ids (or nil) is printed to the console when I run the code.
Thanks!
Because your functions should be returning strings, but they are actually returning the result of
puts "something"do this instead:
Then when you do
puts obj.w00t, it will perform the action, and return the string.