从代表局部变量的字符串中获取值 [英] Get value from string representing local variable

查看:77
本文介绍了从代表局部变量的字符串中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

variable = 22
"variable".to_variable?

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

How can I get the value 22 form the string?

推荐答案

您可以使用eval.

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

但是 eval可能令人讨厌.如果您不介意声明实例变量,也可以执行以下操作:

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

这篇关于从代表局部变量的字符串中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆