1
$\begingroup$

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".

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

2 Answers 2

1
$\begingroup$

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"*)
$\endgroup$
3
  • 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$ Commented 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.
    Commented Jul 24, 2014 at 17:25
  • $\begingroup$ FYI Symbol does the same job as ToExpression here. $\endgroup$
    – masterxilo
    Commented Aug 8, 2016 at 7:16
0
$\begingroup$

Another approach

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

Your Answer

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

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