I have recently learned how to create classes, although I am not ENTIRELY sure where and why I should use them. I'd use them to create objects, which have similar methods/properties.
I tried making a gag code, but I stumbled upon a question I can't find an answer to.
class Person
def initialize(name,health)
@name = name
@hp = health
end
def kick
@hp -= 1
if (@hp <= 0)
puts "#{@name} got REKT!"
end
end
end
#Friends
michael = Person.new("Michael", 10)
10.times { michael.kick }
Even though this code works, I'm wondering if it is possible to use/call mihchael's hp outside the class? Perhaps sort of like a hash? michael[@hp]
? But this doesn't work, even if i set hp to be a global variable.
Should all if/else statements who check object's properties be inside the class?
Thank you very much