Quick Tip - convert a string to variable
Posted by Vince Wadhwani on Apr 09, 2008
Ok, so you already know that you can convert strings to other types of objects using Ruby's powerful tools. "3".to_i will give you an integer (3) while "3".to_f will give you a float. But if you want to convert a string to a variable? For instance if you're sending a call to your model and want to dynamically generate a variable? I wish it were as simple as "myvariable".to_var but it's not...
In this case we'll have to use instance_variable_set to do the trick:
instance_variable_set("@foo", my_value)
Or, to dynamically create that variable name instead of using foo, just do:
instance_variable_set("@#{my_var}", my_value)
Maybe one day we'll be able to just do myvar.to_var but until then, the above should work.