From: "F. Senault" Date: 2008-03-16T05:34:55+09:00 Subject: Re: How to iterate through instance attribute names (attr_accessor) Le 15 mars 2008 � 20:21, Stefano Crocco a �crit : > Of course, you can also keep an array of the names of those instance variables > for which a validation method exists and use the following code: > > def validate > [:a, :b, :c, :d].each{|v| send "validate_#{v}"} > end You can metaprogram your way around it too. Full example (that can surely be improved) : module Kernel def attr_with_validation(*atts) unless method_defined? :validate class_eval <<-_EOE @_validations = [] def self.validations @_validations end def validate self.class.validations.each do |v| self.send("validate_\#{v}") end end _EOE end atts.each do |att| class_eval <<-_EOE @_validations << :#{att} def #{att} @#{att} end def #{att}=(v) @#{att} = v end _EOE end end end class Toto attr_with_validation :a, :b attr_with_validation :c def validate_a() ; raise if @a.nil? ; end def validate_b() ; raise if @b.nil? ; end def validate_c() ; raise if @c.nil? ; end def initialize(a) @a = a end end t = Toto.new("I'm a") t.b = "Hoy b" puts t.a puts t.b t.validate Result is : I'm a Hoy b ./validate.rb:38:in `validate_c': unhandled exception from (eval):7:in `send' from (eval):7:in `validate' from (eval):6:in `each' from (eval):6:in `validate' from ./validate.rb:51