1

I have a list of instances of a class and I have a hash with changes I’d like to apply to these instances. I can’t figure how to access member variable which name I have in list of changes.

E.g.

class Foo
  attr_accessor: foo
  def initialize value
    @foo = value
  end
end

f = Foo.new("bar")

I can obviously access @foo with f.foo, but say I have list of changes in form like changes = {"foo" => "baz"}.

Now I wonder wheter there is a way to do something like this:

changes.each do |k,v|
  f.k = v
end

to have f.foo changed to "baz".

Mr. Tao
  • 843
  • 8
  • 17

1 Answers1

1

send method can help you assign attributes dynamically.

changes.each do |k,v|
  f.send("#{k}=", v)
end
pangpang
  • 8,581
  • 11
  • 60
  • 96