[英]Convert a string literal to a variable name
I want to create an instance of a class with the name of a string. 我想用字符串名称创建一个类的实例。 For example: 例如:
sub_string = "tropical"
string = "forest.#{sub_string}"
My class Instance should be foresttropical = Class_name.new
or forest_tropical = Class_name.new
. 我的类实例应为foresttropical = Class_name.new
或forest_tropical = Class_name.new
。
I want to create a class instance with the variable name foresttropical
or foresttropical
. 我想使用变量名称foresttropical
或foresttropical
创建一个类实例。 Is there any way to do it? 有什么办法吗?
I am using: 我在用:
constantized_var = "forestarea#{x}".capitalize.constantize
constantized_var = Class_name.new
In Plane, I want it to be like this: 在飞机上,我希望它像这样:
x = "tropical"
"forestarea#{x}" = ClassName.new equals forestareatropical = ClassName.new
x = "subtropical"
"forestarea#{x}" = ClassName.new
But it is giving me an error: 但这给了我一个错误:
uninitialized constant Forestareatropical
If your class name is ForestTropical then you can do like this to create new class instance. 如果您的类名称为ForestTropical,则可以这样创建新的类实例。
s1 = "forest"
s2 = "tropical"
new_instance = "#{s1}_#{s2}".classify.constantize.new
# new_instance will be the new instance of your class ForestTropical
I hope this helps. 我希望这有帮助。
Edit 编辑
As per your requirements it ll be something like this 根据您的要求,它将是这样的
x = "tropical"
instance_variable_set("@forestarea#{x}",ClassName.new)
x = "subtropical"
instance_variable_set("@forestarea#{x}",ClassName.new)
I would avoid forest.tropical
as a name for your object, because in Ruby syntax that looks like you are calling a method called tropical
on an instance called forest
which I don't think is what you want here. 我会避免forest.tropical
为您的对象的名称,因为在Ruby的语法,看起来像你调用一个方法叫做tropical
的一个实例称为forest
,我不认为是你想要的这里。 So, stick with forest_tropical
as your instance name. 因此,请坚持使用forest_tropical
作为实例名称。
You might try using instance_variable_set
here: 您可以尝试在此处使用instance_variable_set
:
sub_string = "tropical"
string = "forest_#{sub_string}"
instance_variable_set('@'+string, ClassName.new)
Now you have @forest_tropical
which is an instance of the ClassName
class. 现在,您拥有@forest_tropical
,它是ClassName
类的实例。
Or, according to your edit, you can do: 或者,根据您的编辑,您可以执行以下操作:
x = "tropical"
instance_variable_set("@forestarea#{x}", ClassName.new)
x = "subtropical"
instance_variable_set("@forestarea#{x}", ClassName.new)
Now you have two instance variables, @forestareatropical
and @forestareasubtropical
both of the ClassName class. 现在,您有两个实例变量,分别为ClassName类的@forestareatropical
和@forestareasubtropical
。
maybe you should consider using hashes with appropriate keys instead. 也许您应该考虑使用带有适当键的哈希值来代替。 Since your instance variable names are dynamic anyway, I assume that they will be used in a dynamic context, and for this hashes are better suited. 由于您的实例变量名称始终是动态的,因此我假设它们将在动态上下文中使用,因此,此哈希更适合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.