On Wed, Feb 27, 2013 at 6:36 PM, Shareef J. <[email protected]> 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/

-- 
[email protected] | 
https://groups.google.com/d/forum/ruby-talk-google?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"ruby-talk-google" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to