Using a string as a variable at run time

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}")

Leave a Comment