如何使用访问者访问成员变量哪个名称在Ruby中的变量中传递? [重复]

时间:2022-07-06 00:42:21

This question already has an answer here:

这个问题在这里已有答案:

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"}.

我可以使用f.foo显然访问@foo,但是我说我有变化列表,如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".

将f.foo改为“baz”。

1 个解决方案

#1


send method can help you assign attributes dynamically.

send方法可以帮助您动态分配属性。

changes.each do |k,v|
  f.send("#{k}=", v)
end

#1


send method can help you assign attributes dynamically.

send方法可以帮助您动态分配属性。

changes.each do |k,v|
  f.send("#{k}=", v)
end