Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将实例变量动态命名为Ruby_Ruby_Variables_Dynamic_Naming - Fatal编程技术网

将实例变量动态命名为Ruby

将实例变量动态命名为Ruby,ruby,variables,dynamic,naming,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 我该怎么做呢?你真的不能 你可以玩eval,但实际上,它不可读 使用正确的if或使用哈希 # With Hash: values =

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

def instance(instance)
    @instance = instance #@instance isn't actually a variable called @instance, rather a variable called @whatever was passed as an argument
end
我该怎么做呢?

你真的不能

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

如果我理解正确,您希望使用实例变量集:

class A
end

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

a.instance_variable_get("@whatever") #=> "foo"
使用实例变量集

或者,如果您不希望调用方必须提供“@”:

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

怎样你到底是什么意思?他的意思是:var=:a;hash={var=>foo'};hash[var]=“条”;hash[var];我决不会建议使用eval来实现这一点。这是一个设计缺陷,eval在坏人手中是危险的;可能重复的
varname = 'foo'
value = 'bar'
self.instance_variable_set "@#{varname}", value
@foo   # => "bar"