我想要做的是动态命名变量,例如:
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"