From: Jay Levitt Date: 2007-08-29T14:40:03+09:00 Subject: Re: idiomatic way to assign if not nil? On Aug 28, 10:34 pm, Joel VanderWerf wrote: > Jay Levitt wrote: > > user.login = options[:login] if options[:login] > > user.password = options[:password] if options[:password] > > user.other = options[:other] if options[:other] > > > Felt kinda repetitive. I guess I could DRY that up in an eval loop. > > No need for eval... > > [:login, :password, :other].each do |key| > user.send "#{key}=", options[key] if options.key?(key) > end Perfect! In fact, I'll go even better: User.protected_attributes.each do |key| user.send "#{key}=", options[key] if options.key?(key) end Now I don't have to update my tests when I add attr_protected attributes to my model.