Using a string as a variable at run time

前端 未结 6 1617
悲&欢浪女
悲&欢浪女 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:21

    Now simply using instance_variable_set method, you can create a instance variable at runtime.

    instance_variable_set('@' + 'users', User.all)
    
    0 讨论(0)
  • 2020-12-05 00:24

    As Jason Watkins says, a lot of people might be quick to use eval() first thing and this would be a serious mistake. Most of the time you can use the technique described by Tack if you've taken care to use a class instance variable instead of a local one.

    Local variables are generally not retrievable. Anything with the @ or @@ prefix is easily retrieved.

    0 讨论(0)
  • 2020-12-05 00:25

    I don't mean to be negative, but tread carefully. Ruby gives you a lot of features for highly dynamic programming such as define_method, storing blocks as Proc objects to be called later, etc. Generally these are cleaner code and far safer. 99% of the time using eval() is a mistake.

    And absolutely never use eval() on a string that contains user submitted input.

    0 讨论(0)
  • 2020-12-05 00:28

    If you can forgive an @ sign in front of the variable name, the following will work:

    variable_name = ... # determine user-given variable name
    instance_variable_set("@#{variable_name}", :something)
    

    This will create a variable named @whatever, with its value set to :something. The :something, clearly, could be anything you want. This appears to work in global scope, by declaring a spontaneous Object instance which binds everything (I cannot find a reference for this).

    The instance_variable_get method will let you retrieve a value by name in the same manner.

    instance_variable_get("@#{variable_name}")
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 00:34

    You can use eval() for this provided that you've declared your variable first:

    >> foo = []
    >> eval("foo")[1] = "bar"
    >> foo[1]
    => "bar"
    

    Here are the docs.

    0 讨论(0)
提交回复
热议问题