可以在ruby中做动态变量吗?

我可以通过其他方式实现这种动态性,但它让我很好奇。 在Ruby中是否有类似的机制?

$varname = "hello"; $$varname = "world"; echo $hello; //Output: world 

您可以使用eval实现类似的function

 x = "myvar" myvar = "hi" eval(x) -> "hi" 

它只适用于实例变量(和类变量):

 class MyClass def initialize @varname = :"@hello" instance_variable_set @varname, "world" end def greet puts instance_variable_get(@varname) end end MyClass.new.greet #=> "world" 

对于局部变量,您必须使用eval