1
$\begingroup$
  • 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?

$\endgroup$
2
$\begingroup$

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.

$\endgroup$
1
$\begingroup$

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

$\endgroup$
1
$\begingroup$

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"

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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