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]]


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

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

2 Answers 2


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]];
(*Out[2]="some words"*)
  • 1
    $\begingroup$ 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"] $\endgroup$
    – seismatica
    Jul 23, 2014 at 20:02
  • $\begingroup$ @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. $\endgroup$
    – Jason B.
    Jul 24, 2014 at 17:25
  • $\begingroup$ FYI Symbol does the same job as ToExpression here. $\endgroup$
    – masterxilo
    Aug 8, 2016 at 7:16

Another approach

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.