Gers defender Bilel Mohsni netted twice, either side of the Honest Men's equaliser, scored by Alan Forrest - younger brother of Celtic winger James.
The triumph moves the new third-tier champions to 98 points and leaves just them with just two fixtures - Stranraer at home and Dunfermline away - to negotiate as they seek to complete their league campaign without suffering defeat.
Ayr were one of three teams not to have scored against Ally McCoist's side as they steamrollered their way to promotion.
And it looked as though their miserable record against the fallen Glasgow giants would continue as Mohsni headed in from a corner on 54 minutes.
But Forrest then left the Ibrox crowd - well short of the 40,651 announced by the hosts - stunned when he made the most of a slip up by Arnold Peralta to level for the Somerset side on 69 minutes.
However, normal service was resumed for McCoist's men when Mohsni pounced on a loose ball inside the six-yard box six minutes from the end to smash home his 12th goal of the season.