Forum: Ruby Using Object#send to update instance variables

Posted by Shareef J. (shareef_j)
on 2013-02-27 18:35
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
Posted by Robert Klemme (robert_k78)
on 2013-03-02 18:03
(Received via mailing list)
On Wed, Feb 27, 2013 at 6:36 PM, Shareef J. <lists@ruby-forum.com> 
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 /\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
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.