From: Kent Dahl Date: 2002-08-09T06:23:21+09:00 Subject: Re: Variable validation Chris Morris wrote: > > I've got a class that has a number of instance variables, some of which must > be set prior to calling a save function to write these off somewhere else. > I'm doing the following: > > def check_required > if @password == nil or @password.empty? > or @firstName == nil or @firstName.empty? > or @lastName == nil or @lastName.empty? > or @nickName == nil or @nickName.empty? > or @email == nil or @email.empty? > raise RequiredDataMissingError('') > end > > .. but this smells. If all these are accessible from the outside in reader methods, you could use an array of symbols and send: class RequiredDataMissingError < Exception end class X MANDATORY_FIELDS = [ :password, :firstName, :lastName, :nickName, :email ] attr_accessor *MANDATORY_FIELDS def check_required if MANDATORY_FIELDS.find{|field| value = self.send(field) value == nil or value.empty? } then raise RequiredDataMissingError end end end This does add a methodcall indirection, which could hurt you performancewise, but you seem to be (rightfully) trying to optimize for eyeball time :-) -- (\[ Kent Dahl ]/)_ _~_ __[ http://www.stud.ntnu.no/~kentda/ ]___/~ ))\_student_/(( \__d L b__/ NTNU - graduate engineering - 5. year ) ( \__\_�|�_/__/ ) _)Industrial economics and technological management( \____/_�_\____/ (____engineering.discipline_=_Computer::Technology___)