This question already has an answer here:
这个问题在这里已有答案:
- Is there a 'variable_get' method? If not, how can I create my own? 2 answers
有'variable_get'方法吗?如果没有,我该如何创建自己的? 2个答案
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
#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