How test value of a command with `\ifthenelse` and `\equal`?
The code doesn't work because you're using wrong syntax for \ifthenelse
.
Please check the syntax:
\documentclass{article}
\newcommand{\thing}{whatever}
\usepackage{ifthen}
\ifthenelse{\equal{\thing}{\string whatever}}
{% True case
\newcommand{\result}{thing is `whatever'.}%
}
{% false case
\newcommand{\result}{thing is something else.}%
}
\begin{document}
\result
\end{document}
This will print
this is something else.
because \string
will make the w
in the second argument different from the w
in the (expansion of the) first argument to \equal
.
Removing \string
will give the expected result
This is ‘whatever’.
You seem to be using
\ifthenelse{<test>}{{<code for true>}{<code for false>}}
but this is not the right way:
\ifthenelse{<test>}{<code for true>}{<code for false>}
is the correct syntax.
In your code the <code for false>
was \par
(because you missed the third argument to \ifthenelse
, so TeX picks up the \par
generated by the blank line). Since the test returns false, nothing is defined.
On the other hand, if you remove \string
so the test returns true, you'd end up with \result
being undefined, because you'd execute two \newcommand
instructions, but both inside a group.
For a more general approach:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\ifstringsequalTF}{mmmm}
{
\str_if_eq:eeTF { #1 } { #2 } { #3 } { #4 }
}
\NewExpandableDocumentCommand{\stringcase}{mO{}m}
{
\str_case_e:nnF { #1 } { #3 } { #2 }
}
\ExplSyntaxOff
\newcommand{\thing}{whatever}
\newcommand{\xyz}{xyz}
\newcommand{\noneoftheabove}{}
\ifstringsequalTF{\thing}{whatever}
{\newcommand{\result}{thing is `whatever'.}}
{\newcommand{\result}{thing is something else.}}
\begin{document}
\result
\stringcase{\thing}[OOPS]{
{whatever}{found whatever}
{xyz}{found xyz}
}
\stringcase{\xyz}[OOPS]{
{whatever}{found whatever}
{xyz}{found xyz}
}
\stringcase{\noneoftheabove}[OOPS]{
{whatever}{found whatever}
{xyz}{found xyz}
}
\end{document}
The optional argument to \stringcase
can be omitted and in case of no match nothing would happen.
Here is a way:
\documentclass{article}
\def\thing{whatever}
\usepackage{ifthen}
\ifthenelse{\equal{\thing}{whatever}}
{\newcommand{\result}{thing is `whatever'.}}
{\newcommand{\result}{thing is something else.}}
\begin{document}
\result
\end{document}
Output:
thing is `whatever'.