If \ensuremath were defined as
\newcommand{\ensuremath}[1]{%
\ifmmode
#1
\else
$#1$ %<--- space here!
\fi
}
like you seem to believe, then your expectation would be correct: when defining
\newcommand{\foo}{\ensuremath{foo}}
and using \foo in text mode, the usual TeX rules would gobble the space after \foo but the space would be introduced by the (supposed) definition of \ensuremath.
The fact is, \ensuremath is not defined that way:
\DeclareRobustCommand{\ensuremath}{%
\ifmmode
\expandafter\@firstofone
\else
\expandafter\@ensuredmath
\fi}
\long\def\@ensuredmath#1{$\relax#1$}
and the expansion doesn't introduce any space.
(Question to the audience: why \long?)
\textsc? – Sigur Apr 22 '22 at 18:04x_{\mathrm{Y}}instead?! – Sigur Apr 22 '22 at 18:05_\text..always use braces. It might work here and now, but noone has promised that it will keep working. The braced_{...}always will. – daleif Apr 22 '22 at 19:20\yis a command terminator and is removed. – Herb Schulz Apr 22 '22 at 19:45\ensuremath. It's simply because TeX swallows spaces after control sequences. In the line with$\x$the math mode helps you avoid this effect. Inspacing \y differentthe space is swallowed. See also https://tex.stackexchange.com/q/31091/35864 – moewe Apr 22 '22 at 19:46