Ruby – Using a string as a variable at run time


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?

Best Solution

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.