从表示局部变量的字符串中获取值[duplicate]

时间:2022-02-28 11:44:46

This question already has an answer here:

这个问题在这里已有答案:

I have a local variable name as a string, and need to get its value.

我有一个本地变量名称作为字符串,需要获取其值。

variable = 22
"variable".to_variable?

How can I get the value 22 form the string?

如何从字符串中获取值22?

3 个解决方案

#1


1  

You can use eval.

你可以使用eval。

variable = 22
eval("variable")
# => 22 

However eval can be nasty. If you dont mind declaring an instance variable, you can do something like this too:

然而,评估可能是令人讨厌的。如果你不介意声明一个实例变量,你也可以这样做:

@variable = 22
str = "variable"
instance_variable_get("@#{str}")
# => 22

#2


19  

binding.local_variable_get("variable")
# => 22

#3


1  

use eval() method:

使用eval()方法:

variable = 22
eval "variable" #"variable".to_variable?
# => 22

#1


1  

You can use eval.

你可以使用eval。

variable = 22
eval("variable")
# => 22 

However eval can be nasty. If you dont mind declaring an instance variable, you can do something like this too:

然而,评估可能是令人讨厌的。如果你不介意声明一个实例变量,你也可以这样做:

@variable = 22
str = "variable"
instance_variable_get("@#{str}")
# => 22

#2


19  

binding.local_variable_get("variable")
# => 22

#3


1  

use eval() method:

使用eval()方法:

variable = 22
eval "variable" #"variable".to_variable?
# => 22