Using Object#send to update instance variables

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

On Wed, Feb 27, 2013 at 6:36 PM, Shareef J. [email protected]
wrote:

@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 /\[email protected]*/, ‘@’
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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs