将实例变量动态命名为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"