动态命名实例变量 Ruby



我想做的是动态命名变量,如下所示:

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

我该怎么做?

使用 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"
如果我

理解正确,您想使用"instance_variable_set":

class A
end
a = A.new
a.instance_variable_set("@whatever", "foo")
a.instance_variable_get("@whatever") #=> "foo"

你真的不能。

你可以玩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"

最新更新