From: Raul Parolari Date: 2007-11-12T14:30:46+09:00 Subject: Re: Controlling attribute setting in a Struct unknown wrote: > 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 > ... You just need to redefine the setter attribute; we can automate the production of the setter attributes as follows (I assume that the maximum has the same value for all attributes, else this would need to be modified a bit): class MyMaxBoundedStruct < Struct.new(:life, :strength, :charisma, :weapon) # class variable (depending on Spec, a Constant could be used) @@maximum = 1000 arr = %w[life strength charisma weapon] arr.each do |m| define_method("#{m}=") do |val| if val < @@maximum super(val) else raise ArgumentError, "#{m} set above maximum" end end end end rabbit = MyMaxBoundedStruct.new rabbit.life = 999 rabbit.weapon = 10 p rabbit.life # => 999 rabbit.life = 1000 # => ArgumentError: life set above maximum -- Posted via http://www.ruby-forum.com/.