Using a string as a variable at run time

前端 未结 6 1616
悲&欢浪女
悲&欢浪女 2020-12-05 00:20

I have a string, which has been created at runtime. I want to use this string as a variable to store some data into it. How can I convert the string into a variable name?

6条回答
  •  执笔经年
    2020-12-05 00:32

    Rather than do that directly, why not consider using a hash instead. The string would be the key, and the value you want to store would be the value. Something like this:

    string_values = { }
    some_string = params[:some_string]       # parameter was, say "Hello"
    string_values[some_string] = 42
    string_values                            # { 'Hello' => 42 }
    some_number = string_values[some_string]
    some_number                              # 42
    

    This has a couple of benefits. First, it means you're not doing anything magic that might be hard to figure out later. Second, you're using a very common Ruby idiom that's used for similar functionality throughout Rails.

提交回复
热议问题