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

后端 未结 2 662
旧巷少年郎
旧巷少年郎 2020-12-29 05:25

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 speci

相关标签:
2条回答
  • 2020-12-29 06:19

    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 讨论(0)
  • 2020-12-29 06:20

    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 
    
    0 讨论(0)
提交回复
热议问题