Calling a function!

Source is attached.

I created a Damage method and I would like to Change the value of my
Creature objects hp every time I damage them. I get an error… Please
help me guys I just want to practice programming.

On Sat, Jan 7, 2012 at 1:26 PM, Levi H. [email protected]
wrote:

Source is attached.

I created a Damage method and I would like to Change the value of my
Creature objects hp every time I damage them. I get an error… Please
help me guys I just want to practice programming.

You should create the damage method inside the class, so that you can
say:

hero.damage

If you do that, you will have direct access to the instance variables
of that creature: @name, @attack, @hp, so you could do this:

class Creature
attr_accessor :name, :attack, :hp

def damage
@hp = @hp - 5
end
end

hero = Creature.new
hero.name = “Levi”
hero.attack = 10
hero.hp = 100

frog = Creature.new
frog.name = “Frog”
frog.attack = 1
frog.hp = 10

rat = Creature.new
rat.name = “Rat”
rat.attack = 3
rat.hp = 20

hero.damage
puts hero.hp

A good idea would be to be able to pass a value to the damage method
that represents how much damage is made. Replace the above damage
definition with:

def damage amount
@hp = @hp - amount
end

Another good idea would be to create a constructor for Creature, so
that you initialize the values at once, instead of having to call
hero.name= hero.attack= and hero.hp=, cause if you forget to call one,
the hero would be in a wrong state. For example, you can find that the
hp is nil, and the damage method wouldn’t work. You create a
constructor defining an initialize method like this:

class Creature
attr_reader :name, :attack, :hp

def initialize name, attack, hp
@name = name
@attack = attack
@hp = hp
end

def damage amount=5 #this means that amount is optional, and if not
passed it will be 5
@hp -= amount
end
end

hero = Creature.new “Levi”, 10, 100 #we pass the initial values to the
constructor
hero.damage 2
puts hero.hp

Jesus.

Thank you very much Jesus! This is really helpful and exactly what I
needed. =)