  Denote by $p(n)$ the number of partitions of $n$ and by $N(a,M;n)$ the number
of partitions of $n$ with rank congruent to $a$ modulo $M$. We find and prove a
general formula for Dyson's ranks by considering the deviation of the ranks
from the average: \begin{equation*} D(a,M) := \sum_{n=
0}^{\infty}\left(N(a,M;n) - \frac{p(n)}{M}\right) q^n. \end{equation*} Using
Appell--Lerch sum properties we decompose $D(a,M)$ into modular and mock
modular parts so that the mock modular component is supported on certain
arithmetic progressions, whose modulus we can control. Using our decomposition,
we show how our formula gives as a straightforward consequence Atkin and
Swinnerton-Dyer's results on ranks as well as Bringmann, Ono, and Rhoades's
results on Maass forms. We also apply our techniques to a variation of Dyson's
ranks due to Berkovitch and Garvan.
