在Ruby中使用变量的值作为另一个变量名 [英] Using the value of a variable as another variables name in Ruby

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

问题描述

我刚开始学习Ruby,我编写了一个程序,该程序生成一些数字并将其分配给变量@ one,@ two,@ three等.然后,用户可以通过输入变量来指定要更改的变量名称(例如一个).然后,我需要做类似"@ [valueofinout] = asd"的操作.我将如何执行此操作,是否有更好的方法可以阻止我正在考虑的方法?我找到了

I'm just starting out in learning Ruby and I've written a program that generates some numbers and assigns them to variables @one, @two, @three etc. The user can then specify a variable to change by inputting it's name (e.g one). I then need to do something like '@[valueofinout] = asd'. How would I do this, and is there a better way as the way I'm thinking of seems to be discouraged? I've found

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

但是我不完全理解为什么需要第二行.就我而言,我会使用类似的

but I don't completely understand why the second line is needed. In my case would I use something like

@one = "21"
input = "one"
input = "@" + input
changeto = "22"
eval(input) -> changeto

推荐答案

使用instance_variable_set(

尽管如此,在大多数情况下,您应该将普通的Ruby变量与用户正在与之交互的变量分开.如何创建用户变量哈希,例如

In most cases though, you should separate your normal Ruby variables from the variables your user is interacting with. How about creating a Hash of user variables, e.g.

@uservars = { 'one' => 1, 'two' => 2 }
two = @uservars['two']   # Look up 'two' variable

varname = "myvar"
@uservars[varname] = 5   # Set a variable by name
value = @uservars[varname]  # Get a variable by name 

这篇关于在Ruby中使用变量的值作为另一个变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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