简体   繁体   English

在Ruby中使用变量的值作为另一个变量名

[英]Using the value of a variable as another variables name in Ruby

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 (eg one). 我刚开始学习Ruby,并且编写了一个程序,该程序生成一些数字并将其分配给变量@ one,@ two,@ three等。然后,用户可以通过输入变量名称来指定要更改的变量(例如一)。 I then need to do something like '@[valueofinout] = asd'. 然后,我需要做类似“ @ [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

Use instance_variable_set ( rubydoc ) 使用instance_variable_setrubydoc

instance_variable_set("@" + varname, value)

In most cases though, you should separate your normal Ruby variables from the variables your user is interacting with. 不过,在大多数情况下,您应该将普通的Ruby变量与用户正在与之交互的变量分开。 How about creating a Hash of user variables, eg 如何创建用户变量的哈希,例如

@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 

Instance variables can be retrieved via this method: 实例变量可以通过以下方法检索:

input = instance_variable_get("@one")

After this, in your case you'll have input equal to "21". 此后,对于您来说,您将input等于“ 21”的input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM