问题描述
通常,如何获得对我在字符串中具有其名称的对象的引用?
In general, how can I get a reference to an object whose name I have in a string?
更具体地说,我有一个参数名称列表(成员变量-动态生成的,因此我不能直接引用它们).
More specifically, I have a list of the parameter names (the member variables - built dynamically so I can't refer to them directly).
每个参数都是一个具有from_s
方法的对象.
Each parameter is an object that also has an from_s
method.
我想做类似以下的事情(这当然是行不通的...):
I want to do something like the following (which of course doesn't work...):
define_method(:from_s) do | arg |
@ordered_parameter_names.each do | param |
instance_eval "field_ref = @#{param}"
field_ref.from_s(param)
end
end
推荐答案
最惯用的方法是:
some_object.instance_variable_get("@#{name}")
无需使用+
或intern
; Ruby会很好地处理这个问题.但是,如果您发现自己进入另一个对象并拉出其ivar,则很有可能破坏了封装.
There is no need to use +
or intern
; Ruby will handle this just fine. However, if you find yourself reaching into another object and pulling out its ivar, there's a reasonably good chance that you have broken encapsulation.
如果您明确想要访问ivar,则正确的做法是使其成为访问器.请考虑以下内容:
If you explicitly want to access an ivar, the right thing to do is to make it an accessor. Consider the following:
class Computer
def new(cpus)
@cpus = cpus
end
end
在这种情况下,如果您执行Computer.new
,则将被迫使用instance_variable_get
到达@cpus
.但是,如果您这样做,则可能意味着@cpus
是公开的.您应该做的是:
In this case, if you did Computer.new
, you would be forced to use instance_variable_get
to get at @cpus
. But if you're doing this, you probably mean for @cpus
to be public. What you should do is:
class Computer
attr_reader :cpus
end
现在您可以执行Computer.new(4).cpus
.
请注意,您可以重新打开任何现有类,并将私有的ivar变成阅读器.由于访问器只是一种方法,因此您可以Computer.new(4).send(var_that_evaluates_to_cpus)
Note that you can reopen any existing class and make a private ivar into a reader. Since an accessor is just a method, you can do Computer.new(4).send(var_that_evaluates_to_cpus)
这篇关于获取给定名称的实例变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!