在运行时使用字符串作为变量 [英] Using a string as a variable at run time

查看:37
本文介绍了在运行时使用字符串作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,它是在运行时创建的.我想使用这个字符串作为变量来存储一些数据.如何将字符串转换为变量名?

I have a string, which has been created at runtime. I want to use this string as a variable to store some data into it. How can I convert the string into a variable name?

推荐答案

如果你能原谅变量名前面的@符号,下面的方法就可以了:

If you can forgive an @ sign in front of the variable name, the following will work:

variable_name = ... # determine user-given variable name
instance_variable_set("@#{variable_name}", :something)

这将创建一个名为 @whatever 的变量,其值设置为 :something.:something 显然可以是你想要的任何东西.这似乎在全局范围内工作,通过声明一个自发的 Object 实例来绑定所有内容(我找不到对此的引用).

This will create a variable named @whatever, with its value set to :something. The :something, clearly, could be anything you want. This appears to work in global scope, by declaring a spontaneous Object instance which binds everything (I cannot find a reference for this).

instance_variable_get 方法将让您以相同的方式按名称检索值.

The instance_variable_get method will let you retrieve a value by name in the same manner.

instance_variable_get("@#{variable_name}")

这篇关于在运行时使用字符串作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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