-1

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

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

我怎样才能做到这一点?

4

3 回答 3

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"
于 2012-05-05T02:11:52.703 回答
3

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

class A
end

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

a.instance_variable_get("@whatever") #=> "foo"
于 2012-05-05T02:10:09.393 回答
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"
于 2012-05-05T01:48:51.867 回答