名称实例变量动态Ruby

时间:2012-05-05 01:45:16

标签: ruby variables dynamic naming

我想要做的是动态命名变量,如:

def instance(instance)
    @instance = instance #@instance isn't actually a variable called @instance, rather a variable called @whatever was passed as an argument
end

我该怎么做?

3 个答案:

答案 0 :(得分:5)

使用instance_variable_set

varname = '@foo'
value = 'bar'
self.instance_variable_set varname, value
@foo   # => "bar"

或者如果您不希望呼叫者必须提供'@':

varname = 'foo'
value = 'bar'
self.instance_variable_set "@#{varname}", value
@foo   # => "bar"

答案 1 :(得分:2)

如果我理解正确,你想使用“instance_variable_set”:

class A
end

a = A.new
a.instance_variable_set("@whatever", "foo")

a.instance_variable_get("@whatever") #=> "foo"

答案 2 :(得分:0)

你真的不能。

您可以使用eval,但实际上,它无法读取。

使用正确的if或使用哈希。

# With Hash:
values = {}
a = :foo
values[a] = "bar"
values[:foo] # => "bar"

# With if
calc = "bar"
if a_is_foo
  foo = calc
else
  oof = calc
end
foo # => "bar"