Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
  • case1

    Options[f] = {"t" -> "0"};
    f[___, OptionsPattern[]] :=  StringReplace["content", "t" :> OptionValue["t"]]
  • case2

    rule = {"t" -> OptionValue["t1"]};
    Options[gg] = {"t1" -> "T1", "t2" -> "1"};
    gg[___, OptionsPattern[]] := StringReplace["content", rule]

Here OptionValue couldn't get the value of "t1" So, how to make case 2 works like case 1?

I found one solution is


Any simpler methods?

share|improve this question

It would help if you outlined you intended use of this behavior, as without that it is not clear what is and is not helpful.

Single function case

You can use the two-argument form of OptionValue:

rule = {"t" :> OptionValue[gg, "t1"]};  (* note RuleDelayed *)

Options[gg] = {"t1" -> "T1", "t2" -> "1"};
gg[___, OptionsPattern[]] := StringReplace["content", rule]


This works just fine with a single function (gg), but it is not directly applicable if you intend to use this rule in multiple functions.

Arbitrary function case

As you apparently understand based on your workaround, the single-argument OptionValue expression must appear literally on the right-hand-side of a rule or definition with OptionsPattern, which your use of Evaluate does. Any other method that does the same can be used, e.g.:

With[{rule = rule},
  gg[___, OptionsPattern[]] := StringReplace["content", rule]


(gg[___, OptionsPattern[]] := StringReplace["content", #]) & @ rule

For the arbitrary-function case I see no simpler method than these.

share|improve this answer

Perhaps not what you are after:

op[] := Function[x, 
   x /. MapThread[
     Rule[#1, (#2)] &, {{"t", "t1", "t2"}, 
      Thread["t" -> {"0", "T1", "1"}]}]];
srf[opts_: "t"] := StringReplace["content", op[][opts]]



yields the default value:




{"con0en0", "conT1enT1", "con1en1"}

share|improve this answer

One solution is to keep OptionValue inside the function :-

rule = {"t" -> "t1"};

Options[gg] = {"t1" -> "T1", "t2" -> "1"};
gg[___, OptionsPattern[]] := StringReplace["content", #1 -> OptionValue[#2] & @@@ rule]



share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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