繁体   English   中英

将字符串文字转换为变量名

[英]Convert a string literal to a variable name

我想用字符串名称创建一个类的实例。 例如:

sub_string = "tropical"
string = "forest.#{sub_string}"

我的类实例应为foresttropical = Class_name.newforest_tropical = Class_name.new

我想使用变量名称foresttropicalforesttropical创建一个类实例。 有什么办法吗?

我在用:

constantized_var = "forestarea#{x}".capitalize.constantize
constantized_var = Class_name.new

在飞机上,我希望它像这样:

x = "tropical"
"forestarea#{x}" = ClassName.new equals forestareatropical = ClassName.new
x = "subtropical"
"forestarea#{x}" = ClassName.new

但这给了我一个错误:

uninitialized constant Forestareatropical

如果您的类名称为ForestTropical,则可以这样创建新的类实例。

s1 = "forest"
s2 = "tropical"
new_instance = "#{s1}_#{s2}".classify.constantize.new
# new_instance will be the new instance of your class ForestTropical

我希望这有帮助。

编辑

根据您的要求,它将是这样的

x = "tropical"
instance_variable_set("@forestarea#{x}",ClassName.new)
x = "subtropical"
instance_variable_set("@forestarea#{x}",ClassName.new)

我会避免forest.tropical为您的对象的名称,因为在Ruby的语法,看起来像你调用一个方法叫做tropical的一个实例称为forest ,我不认为是你想要的这里。 因此,请坚持使用forest_tropical作为实例名称。

您可以尝试在此处使用instance_variable_set

sub_string = "tropical"
string = "forest_#{sub_string}"
instance_variable_set('@'+string, ClassName.new)

现在,您拥有@forest_tropical ,它是ClassName类的实例。

或者,根据您的编辑,您可以执行以下操作:

x = "tropical"
instance_variable_set("@forestarea#{x}", ClassName.new)
x = "subtropical"
instance_variable_set("@forestarea#{x}", ClassName.new)

现在,您有两个实例变量,分别为ClassName类的@forestareatropical@forestareasubtropical

也许您应该考虑使用带有适当键的哈希值来代替。 由于您的实例变量名称始终是动态的,因此我假设它们将在动态上下文中使用,因此,此哈希更适合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM