Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.
  • case1

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

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

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


I found one solution is

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

Any simpler methods?

share|improve this question
add comment

3 Answers 3

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]

gg[1]
"conT1enT1"

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

Or:

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

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

share|improve this answer
add comment

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

Note:

srf[]

yields the default value:

"con0en0"

srf/@{"t","t1","t2"}

yields

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

share|improve this answer
add comment

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]

gg[1]

"conT1enT1"

share|improve this answer
add comment

Your Answer

 
discard

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.