开发者

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 (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


Use instance_variable_set (rubydoc)

instance_variable_set("@" + varname, value)

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 


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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜