Reputation: 138
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!
Upvotes: 2
Views: 483
Reputation: 447
Just remove some puts
. Your methods prints everything on stdout, and you prints their result.
Upvotes: 0
Reputation: 39929
Because your functions should be returning strings, but they are actually returning the result of puts "something"
do this instead:
def w00t
@health += 15
"#{@fname} got w00ted"
end
Then when you do puts obj.w00t
, it will perform the action, and return the string.
Upvotes: 2
Reputation: 1
Every method in Ruby returns a value so the #blam method does return something. In this case it is the value of the last expression: the result of calling puts, which is nil. So when you puts larry.blam
you are puts-ing the return of the last statement, puts, and thus nil.
Upvotes: 0