Joshua Choi
11/12/2007 4:11:00 AM
I'm using a bunch of Struct classes in a program; they're a perfect
way for me to bundle and access attributes. But in one of my
subclasses of Struct, I'm trying to control setting attributes so that
setting an attribute above a certain value causes an effect, like
this:
# All attributes are integers.
MyMaximumBoundedStruct <
Struct.new(:life, :strength, :charisma, :weapon)
@maximum = 1000
def what_happens_when_an_attribute_is_set(attribute_name, new_value)
if new_value <= @maximum
super(attribute, new_value)
else
raise ArgumentError, "#{attribute_name} set above maximum"
end
end
end
rabbit_stats = MyMaximumBoundedStruct.new
rabbit_stats.life = 128 # okay, normal behavior
rabbit_stats.life = 1001 # raises an exception
Is there some method I can override to get this sort of behavior? Or
is this impossible or impractical using Structs (which would make me
sad, because they're otherwise perfect for me)?
Thank you all in advance.