[Tex/LaTex] Comparing an argument to a string when argument is a result of a command with etoolbox

conditionalsetoolboxmacros

I've got an example like that:

\documentclass{article}

\usepackage{etoolbox}

\newcommand{\ab}{a}

\newcommand{\aORb}[1]{%
        \ifstrequal{#1}{a}{"a" was given}{not a}, %
        \ifstrequal{#1}{b}{"b" was given}{not b}%
}

\begin{document}
 begin

     \aORb{\ab{}}

 end
\end{document}

And the output of that code is:

begin
not a, not b
end

However, if I put simply "a" or "b" as an argument to \aORb instead of \ab{} then it works fine.

Is there another command in etoolbox package that will allow me to do such a comparison correctly?

Best Answer

The etoolbox manual states for \ifstrequal on page 17: (emphasis mine)

Compares two strings and executes ⟨true⟩ if they are equal, and ⟨false⟩ otherwise. The strings are not expanded in the test and the comparison is category code agnostic.

So you always compare the string “\ab{}” with “a” and “b”. If you want to allow macros as input you need to expand them manual:

\newcommand{\aORb}[1]{%
        \expandafter\ifstrequal\expandafter{#1}{a}{"a" was given}{not a}, %
        \expandafter\ifstrequal\expandafter{#1}{b}{"b" was given}{not b}%
}

This expands the first token of #1 once before \ifstrequal is processed.

If you want to expand the input completely use:

\newcommand{\aORb}[1]{%
        \edef\mytemp{{#1}}%
        \expandafter\ifstrequal\mytemp{a}{"a" was given}{not a}, %
        \expandafter\ifstrequal\mytemp{b}{"b" was given}{not b}%
}

This expands the input completely using \edef and wraps it in braces, so only one \expandafter is enough.

Then you need to use \aORb{\ab} not \aORb{\ab{}}, because \ab doesn't take an argument the {} would stay and you would compare here “a{}” with “a” and “b”.

Related Question