From: Robert Klemme Date: 2013-03-03T02:02:30+09:00 Subject: Re: Using Object#send to update instance variables On Wed, Feb 27, 2013 at 6:36 PM, Shareef J. wrote: > Hi there, > > been trying to figure this out for a while and wanted to check I had the > cleanest solution. > > I have a class with some instance varaibles that I'd like to update by > iterating over some matching strings pulled from a config file. > > The instance variable are either arrays or strings so I want to append > to the arrays and overwrite the strings. > > Is the following best practice? > > Thanks, Shareef. > > > class Test > attr_accessor :string, :array > > def initialize > @string = String.new > @array = Array.new > end > > def update(method, arg) > if Array === __send__(method) > __send__("#{method}") << arg > else > __send__("#{method}=",arg) > end > end > end The string interpolation is totally superfluous in the Array case. You are also fetching the instance variable twice. Generally I think if you need to mostly update your data via this #update method then storing in a Hash is preferable. Then you do not need to go through these hoops to access data. As an alternative to the code above: def update(name, arg) ivar = name.sub /\A@*/, '@' val = instance_variable.get ivar if Array === val val << arg else instance_variable_set ivar, arg end end And another one Test = Struct.new :string, :array do def initialize self.string = '' self.array = [] end def update(name, arg) val = self[name] if Array === val val << arg else self[name] = arg end end end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/