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

时间:2015-11-24 09:43:29

标签: ruby-on-rails ruby

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

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

3 个答案:

答案 0 :(得分:2)

如果您的班级名称是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)

答案 1 :(得分:2)

我会避免将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)

现在你有两个实例变量,@forestareatropical@forestareasubtropical这两个ClassName类。

答案 2 :(得分:0)

也许你应该考虑使用带有适当键的哈希。由于您的实例变量名称无论如何都是动态的,我假设它们将在动态上下文中使用,并且对于此哈希更适合。