获取给定名称的实例变量的值

一般来说,我怎样才能得到一个对象的引用,它的名字在一个字符串中?

更具体地说,我有一个参数名称的列表(成员变量——动态构建的,所以我不能直接引用它们)。

每个参数都是一个同时具有 from_s方法的对象。

我想做下面这样的事情(当然这是行不通的... ...) :

define_method(:from_s) do | arg |
@ordered_parameter_names.each do | param |
instance_eval "field_ref = @#{param}"
field_ref.from_s(param)
end
end
96290 次浏览

To get an instance variable from the name of an instance variable do:

name = "paramName"
instance_variable_get(("@" + name).intern)

This will return the value of the instance variable @paramName

The most idiomatic way to achieve this is:

some_object.instance_variable_get("@#{name}")

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.

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

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

Now you can do Computer.new(4).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)