You can write a custom setter for it:
class Player
attr_accessor :hitpoints
def hitpoints=(value)
raise 'Not an integer' unless value.is_a? Integer
@hitpoints = value
end
end
You should also use this setter in your initialization method instead of instance variable:
def initialize(hitpoints)
self.hitpoints = hitpoints
end
UPDATE:
About attr_accessor. This method defined both setter and getter method for an attribute. Because you are defining your own setter later in the code, the default one is not needed and may be discarded with attr_reader, as suggested in comments by Stefan and Arup.
I have pretty mixed feelings about this though, as if you were working with somebody else, he will firstly noticed attr_reader at the top of your class and will think - Hey, why is it a read_only attribute? If it is a new developer, it might even cause him to write some nonsense code.
I believe that the code is to show its purpose, hence I would use attr_accessor even if it gives me method redefined warning. This is however a matter of personal preference.