# How does one go from a string to the contents of a variable with the same name?

What command should I use if I want to convert a string to the contents of a variable with the same name as the contents of that string withing a function. ToExpression[] doesn't seem to do it.

func[var_String]:=Module[{var1,var2},var1="some words";var2="other words";ToExpression[var]]

func["var1"]
var1


I want the outcome in this example to be "some words".

• Your example produces "a very big deal" for me (V9.0.1, Mac). Jul 23, 2014 at 19:34
• It's also successful for me (v10.0.0.0, Windows). Jul 23, 2014 at 19:35
• My example was overly simplified. Sorry. Better example above. Jul 23, 2014 at 19:48

What you need is Block instead of Module. It changes the extent to which the variables are localized.

func[var_String] := Block[{var1, var2},var1="some words";var2="other words";ToExpression[var]];
func["var1"]
(*Out[2]="some words"*)

• You can see why Module did not work by evaluating this: Clear[func]; func[var_String] := Module[{var1, var2}, Print[{var1, var2}]; ToExpression[var]]; func["var1"] Jul 23, 2014 at 20:02
• @seismatica, that's a great point, and evaluating the same thing with Block instead 'Module' makes it really clear what the difference is between them, more than reading about lexical versus dynamic scoping. Jul 24, 2014 at 17:25
• FYI Symbol does the same job as ToExpression here. Aug 8, 2016 at 7:16

Another approach

Clear[func]
func[var_String] := Switch[var,
"var1", "some words",
"var2", "other words"];
{func["var1"], func["var2"]}
(* {"some words", "other words"} *)