在Ruby中使用变量的值作为另一个变量名 [英] Using the value of a variable as another variables name in Ruby
本文介绍了在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
推荐答案
查看全文