From: Walter Szewelanczyk Date: 2004-08-14T05:26:20+09:00 Subject: Re: Question: A method for summing several variables Harry Truax wrote: > Lennon, > > Thanks for the quick reply. Unfortunately, I am required to use the box > variables (box1_1, box12_24,...etc.). > > Harry Its not very pretty and it can be optimized quite a bit, but the concept might work for you. $SAFE=3 class SomeClass attr_accessor :box1_1, :box1_2, :box1_3, :box1_4, :box1_5 attr_accessor :box2_1, :box2_2 attr_accessor :box3_1, :box3_2 def initialize @box1_1 = 1 @box1_2 = 2 @box1_3 = "" @box1_4 = 4 @box1_5 = "" @box2_1 = "" @box2_2 = "" @box3_1 = 100 @box3_2 = 200 end #pass in a string for the box you want def sum(box) find_box_variables(box).inject(0){|sum, var| sum+send(var).to_i} end def find_box_variables(box) public_methods.find_all{|var_name| /^#{box}_\d+$/ =~ var_name} end end s = SomeClass.new puts s.sum("box1") puts s.sum("box2") puts s.sum("box3") -------------- OUTPUTS ------------------------- 7 0 300 Hope that helps, Walt -- Walter Szewelanczyk IS Director M.W. Sewall & CO. email : walter@mwsewall.com 259 Front St. Phone : (207) 442-7994 x 128 Bath, ME 04530 Fax : (207) 443-6284